Java 如何使用 Spring Web Mvc 实现注销功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1755143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement Logout feature using Spring Web Mvc
提问by Nirmal
I am new to Spring Web MVC..
我是 Spring Web MVC 的新手。
Can I get some example or online link that shows me how to implement logout feature using spring web mvc ?
我可以获得一些示例或在线链接,向我展示如何使用 spring web mvc 实现注销功能吗?
I don't want to use the in built feature of spring security (i.e. ACEGI)..
我不想使用 Spring Security 的内置功能(即 ACEGI)。
Thanks in advance...
提前致谢...
采纳答案by 30thh
The trick with the session invalidation doesn't work. It seems the Spring authentication buffers the session ID somewhere and accept the COOKIE even, if the session was invalidated.
会话失效的技巧不起作用。如果会话无效,Spring 身份验证似乎在某处缓冲会话 ID 并接受 COOKIE。
Another solution is to clear the Spring security context manually:
另一种解决方案是手动清除 Spring 安全上下文:
public void manualLogout() {
SecurityContextHolder.getContext().setAuthentication(null);
}
Here is the code, how to log in user manually (if somebody needs):
这是代码,如何手动登录用户(如果有人需要):
public void doManualLogin(HttpServletRequest request, String u, String p) {
UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(u, p);
token.setDetails(new WebAuthenticationDetails(request));
Authentication auth = authenticationProvider.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(auth);
}
where the authenticationProvider is the bean from you spring configuration which implements
其中 authenticationProvider 是您的 spring 配置中实现的 bean
org.springframework.security.authentication.AuthenticationProvider
回答by Thomas Jung
You only have to invalidate the session and the user is logged out. This is directly supported by the servlet api: HttpSession.invalidate(). You can write one controller that does only call invalidate.
您只需使会话无效并且用户已注销。这是由 servlet api 直接支持的:HttpSession.invalidate()。您可以编写一个仅调用无效的控制器。
class Logout implements Controller{
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response){
ModelAndView view = //?;
request.getSession().invalidate();
return view;
}
}
回答by Krishna Rao
@Controller
public class LogoutController {
@RequestMapping(value="/logout",method = RequestMethod.GET)
public String logout(HttpServletRequest request){
HttpSession httpSession = request.getSession();
httpSession.invalidate();
return "redirect:/";
}
}
Please use above code to implement logout filter
请使用上面的代码实现注销过滤器