【问题标题】:How to implement Logout feature using Spring Web Mvc如何使用 Spring Web Mvc 实现注销功能
【发布时间】:2009-11-18 10:46:24
【问题描述】:

我是 Spring Web MVC 的新手..

我能否获得一些示例或在线链接,向我展示如何使用 spring web mvc 实现注销功能?

我不想使用 spring security 的内置功能(即 ACEGI)..

提前谢谢...

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

    会话失效的技巧不起作用。似乎 Spring 身份验证在某处缓冲会话 ID 并接受 COOKIE,即使会话无效。

    另一种解决方案是手动清除 Spring 安全上下文:

    public void manualLogout() {
        SecurityContextHolder.getContext().setAuthentication(null);
    }
    

    这里是代码,如何手动登录用户(如果有人需要):

    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);
    }
    

    authenticationProvider 是你实现的 spring 配置中的 bean

    org.springframework.security.authentication.AuthenticationProvider
    

    【讨论】:

      【解决方案2】:

      您只需使会话无效并且用户退出。这由 servlet api 直接支持:HttpSession.invalidate()。您可以编写一个只调用 invalidate 的控制器。

      class Logout implements Controller{
       public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response){
         ModelAndView view = //?;
         request.getSession().invalidate();
         return view;
       }      
      }
      

      【讨论】:

      • 您可以使用 getSession (java.sun.com/javaee/5/docs/api/javax/servlet/http/…) 检查会话是否仍处于活动状态。或者您在会话中处理您的身份验证信息。您必须在拦截器或每个控制器中执行此操作。
      • 您可能还需要清除您设置的所有 cookie 以支持“记住我”功能。否则,您将在下次访问该网站时立即重新登录。
      【解决方案3】:
      @Controller
          public class LogoutController {
      
              @RequestMapping(value="/logout",method = RequestMethod.GET)
              public String logout(HttpServletRequest request){
                  HttpSession httpSession = request.getSession();
                  httpSession.invalidate();
                  return "redirect:/";
              }
      
          }
      

      请使用以上代码实现注销过滤

      【讨论】:

      • 会话到期时如何重定向到登录页面。能否请您提供另一种情况。
      猜你喜欢
      • 1970-01-01
      • 2014-07-02
      • 2015-10-29
      • 2017-10-23
      • 2022-12-25
      • 2011-05-09
      • 2010-10-17
      • 2010-09-18
      • 2017-10-08
      相关资源
      最近更新 更多