The SSM project uses interceptors to realize login authentication

Posted by bschultz on Mon, 24 Jan 2022 00:46:07 +0100

The SSM project uses interceptors to realize login authentication

Login interface implementation

 public User queryUser(String UserName, String Password,HttpServletRequest request, HttpServletResponse response) {
        User user = userMapper.queryUser(UserName,Password);
        if(!StringUtils.isEmpty(user)){
            //1. Get session
            HttpSession session = request.getSession();
            //2. Get sessionid
            String sessionId = session.getId();
            //3. Put the sessionid as the key and the user information user as the value into the session
            session.setAttribute(sessionId,user);
            //4. Save sessionId into the cookie, and "JSESSIONID" is the customized key value
            Cookie cookie = new Cookie("JSESSIONID",sessionId);
            //5. Set the valid path of the cookie
            cookie.setPath(request.getContextPath());
            //6. Return the cookie to the page
            response.addCookie(cookie);
        }
        return user;
    }

Code idea:

1. The User enters the account and password and obtains the User information (User) after successful login

2. Get the session and get the sessionid (Note: each session object has a sessionid)

3. Put the sessionid as the key and the User information (User) as the value into the session

4. Create a cookie object and put "JSESSIONID" as key and sessionId as value into the cookie

5. Set the effective path of the cookie and return the cookie to the page. At this time, the page can receive the cookie information with key as "JSESSIONID" and value as sessionId, as shown in the following figure.

Interceptor class code implementation

public class Filter extends HandlerInterceptorAdapter {
    private static Logger logger = Logger.getLogger(Filter.class);
    /**
     * Method of first entering after entering the interceptor
     * If false is returned, execution will not continue
     * Return true to continue execution
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler)throws Exception
    {
        //1. Define sessionid variable
        String sessionid = "";
        //2. Get the session object
        HttpSession session=request.getSession();
        //3. Get all cookie s on the page
        Cookie[] cookies = request.getCookies();
        //4. Loop through the cookie named "JSESSIONID"
        for(Cookie cookie:cookies){
            if(cookie.getName().equals("JSESSIONID")){
                sessionid = cookie.getValue();
            }
        }
        //5. Obtain user information according to sessionid
        User user = (User) session.getAttribute(sessionid);
        if(StringUtils.isEmpty(user)) {
            logger.info("User not logged in");
            //If the user is not logged in, jump to the login page
            response.sendRedirect("login");
            return false;
        }
        logger.info("User logged in");
        return  true;
    }

}

Code idea:

1. To customize an interceptor class, first inherit the HandlerInterceptorAdapter, override the preHandle method, and write the interceptor logic code in this method

2. Get the cookie array, which contains all cookie information in the browser. Loop through to find the cookie with name "JSESSIONID" and get its value value, which is sessionid

3. Find the user object through the sessionid. If you can get the object certificate that you have logged in, if you can't get the object certificate that you haven't logged in

4. If you have logged in, you can directly access the interface. If you have not logged in, you can jump to the login page to log in

Configuration file implementation

    <!--custom interceptor -->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--Configure the path to intercept-->
            <mvc:mapping path="/**"/>
            <!--The configured login interface is not blocked-->
            <mvc:exclude-mapping path="/user/login"/>
            <!--Specify interceptor classpath-->
            <bean class="com.lishiqi.Util.Filter"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

Configuration meaning:

1. When using interceptors, we must specify which interfaces to intercept. First, we will intercept all interfaces

2. Then we find the problem. At this time, the login interface is also in the interception range, so before we call the login interface normally, he will also intercept and judge whether the user has logged in. At this time, the user must not have logged in, so he will jump to the login interface again. We log in again or jump to the login page, and we can't log in all the time, Therefore, we need to configure the login interface not to intercept

3. Then we specify the interceptor class path we have configured. At this time, we can perform login verification in this class

4. The configuration file is spring MVC XML configuration file

Topics: Java Programmer SSM