SpringMVC's interceptor implements login verification

Looking back at the javaweb learning roadmap I posted earlier today, I found that I have learned more than half of the roadmap, but there is still a long way to go. In the previous blog, I have learned spring's aop, which is implemented by dynamic proxy, and the same is true in springmvc. Today, HandlerInterceptor is used to implement login authorization verification. When we usually make the system, some pages need to be logged in before they can be accessed. One way is to make a login judgment in each request method. At most, the login function is encapsulated, and no new code is added in the future. , this is very inconvenient. In fact, here we can use the interceptor for login verification to determine whether there is a session, and if there is a session, it is concluded that it has been logged in. The interceptor can not only do login, it may also restrict the permissions of pages or tools according to the user role after the login is completed. We can also add another interceptor to judge user permissions and so on. You can also use it for anti-leech. There is a similar implementation in the previous blog of this anti-leech. Today, I will only demonstrate the login.

1. Create a controller

1. The LoginIntercepter class is created here to implement HandlerInterceptor to create a controller. HandlerInterceptor has 3 methods, preHandle, postHandle, afterCompletion, which were also introduced when learning the springmvc workflow before. We do login verification mainly in the preHandle method to verify. Here it is judged whether it is the login page, the login page cannot be blocked, otherwise it will never be able to log in. Then judge whether there is a session, if there is, it will be regarded as a successful login, if not, it will jump to the login page.

package com.cyw.web.Intercepter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginIntercepter implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // TODO Auto-generated method stub
        String requestURI = request.getRequestURI();  
        if(requestURI.indexOf("/login")<=0){  
            //说明处在编辑的页面  
            HttpSession session = request.getSession();  
            String username = (String) session.getAttribute("username" );  
             if (username!= null ){  
                 // Users who log in successfully   
                return  true ;  
            } else {  
                // No login, turn to login interface   
                request.getRequestDispatcher("../view/Login.jsp" ).forward(request,response); 
 //                 response.sendRedirect("../login/login.action" );
                
              
              return false;  
            }  
        }else{  
            return true;  
        }  
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}
View Code

2. The interceptor configuration is configured in spring-mvc.xml

    <mvc:interceptors>
        <mvc:interceptor><mvc:mapping path="/**"/><bean class="com.cyw.web.Intercepter.LoginIntercepter"/></mvc:interceptor> 
        <mvc:interceptor><mvc:mapping path="/**"/><bean class="com.cyw.web.Intercepter.LoginWebRequestInterceptor"/></mvc:interceptor> 
    </mvc:interceptors>
View Code

Two interceptors are configured here, LoginWebRequestInterceptor is also an interceptor.

Second, create a jsp page

Here a login page of login.jsp is created.

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<form action="../login/login.action" method="post">  
         姓名:<input type="text" name="username"> <br><br>  
         密码:   <input type="text" name="password"> <br><br>  
         <input type="submit" value="登陆">  
</form>
</body>
</html>
View Code

3. Create LoginController

The LoginController is created here to receive post requests for login.

package com.cyw.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/login")
public class LoginController {
    @RequestMapping(value = "/login.action",method = RequestMethod.GET)
    public ModelAndView login(HttpServletRequest request,HttpServletResponse response){  
         ModelAndView modelAndView =new ModelAndView("Login");
         return modelAndView;
    }
    @RequestMapping(value = "login.action",method = RequestMethod.POST)
    public String clientLogin(HttpServletRequest request,HttpServletResponse response){ 
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        if(username.equals("cuiyw")&&password.equals("123456")){  
            //登陆成功  
            request.getSession().setAttribute("username",username);  
            return "forward:/hello/testModelAndView";  
        } else {  
             // Login failed   
            return "forward:/login/login.action" ;  
        }  
    }

}
View Code

But the above code will have the problem HTTP Status 405 - Method Not Allowed , Request method 'POST' not supported.

Why does this error occur? I initially thought that there was a problem with the @RequestMapping configuration in LoginController, but I couldn't find it after searching for a long time, and when I entered the page again, it showed that the login was successful, which means that the session is also set, holding The mentality of trying changed the forward in the return to redirect, but I didn't expect it to be successful. This is embarrassing, which involves the difference between forward and redirect.

Fourth, the difference between forward and redirect

Forward process
forwarding, server-side behavior. The web server takes the accepted request, calls the internal method to complete the request processing and forwarding action inside the container, and then responds to the client. Here, the forwarding path must be the url under the same web container, and it cannot be redirected to other web paths Up, the request in its own container is passed in the middle.
The redirect process
redirects, client behavior. The client sends an http request. After the web server accepts it, it sends a 3** status code response and the corresponding new location to the client. The client finds that it is a 3** response and automatically sends a new http request with the new request url. The location address, where the location can be redirected to any URL, since the browser reissues the request, there is no concept of request transmission. The redirect behavior is that the browser makes at least two access requests.

Five, the cause of the problem

The difference between forward and redirect above also introduces the difference between them. Forward uses the same request, but transfers the request to another method for processing. Redirect is to respond to the status code at the beginning of client 3, and then the client again Request, here we log in the post request, and the method = RequestMethod.GET set by the testModelAndView method corresponding to /hello/testModelAndView, there is no post, so a 405 error is reported.

Six, WebRequestInterceptor interceptor

In springmvc, you can also use WebRequestInterceptor as an interceptor. The usage is similar to that of HandlerInterceptor. It is also a real WebRequestInterceptor, and then rewrites the method of the parent class and configures it in spring-mvc.xml. The implemented method names are the same, except HttpServletRequest used in HandlerInterceptor and WebRequest used in WebRequestInterceptor.

7. Summary

In fact, I didn't plan to write an interceptor, because the parameter transfer of springmvc has not been written yet, so the next part is to continue to write the parameter transfer, the interaction between json and Controller.

Guess you like

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