springmvc login interception

Login interception:

    Use the interceptor to complete the login control, specifically intercepting the user's request to determine whether the user has logged in. If the user is not logged in, it will jump to the login interface, and if the user is logged in, it will be released.

    1. First create a login interceptor class LoginInterceptor to implement the HandlerInterceptor interface and implement its three methods, namely preHandle, postHandle, afterCompletion methods, where the preHandle method is changed to   

     @Override

     public boolean preHandle(HttpServletRequest request, HttpServletResponse response,

     Object object) throws Exception {
     // TODO Auto-generated method stub
      System.out.println("preHandle");
      String uri = request.getRequestURI();
      if(!(uri.contains("login")||uri.contains("Login"))){
          if(request.getSession().getAttribute("user")!=null){
                return true;
           }else{
               response.sendRedirect(request.getContextPath()+"/toLogin");
           }
       }else{
          return true;
        }
           return false;
        }

        2. Configure the interceptor in springMVC

        <mvc:interceptors>
                   <mvc:interceptor>
                   <mvc:mapping path="/login"/>
                   <mvc:mapping path="/test"/>
                   <bean class="cn.com.mvc.interceptor.LoginInterceptor"></bean>
                   </mvc:interceptor>
          </mvc:interceptors>

          3. Write the LoginController method

              @RequestMapping("login")
              public String login(Model model, User user,HttpServletRequest request){
                     service = new LoginService();
                     if(service.Login(user)){
                           request.getSession().setAttribute("user", user);
                     }else{
                          model.addAttribute("loginError", "账号或密码错误");
                          return "user/login";
                      }
                      return "redirect:/test";
               }

               Because the interception is the login request, a "/test" request is added to directly jump to the homepage request, and a redirection is added to the login request

               

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324895699&siteId=291194637