Spring framework interceptor (Interceptor)

        The interceptor of SpringMVC is similar to the filter of JavaServlet. It is mainly used to intercept the user's request and do corresponding processing. It is usually applied to authority authentication ( protecting server resources ), logging of request information, and judging whether the user is logged in or not.

Custom Login Interceptor

 1. Create a class and implement the HandlerInterceptor interface , which contains three methods: preHandle, postHandle and afterCompletion.

boolean preHandle() method:

  • Executed before the request reaches the target resource or controller. When the method returns true, the request is allowed to reach the target resource or the next interceptor. When the method returns false, the request is prevented from continuing to access.

void postHandle() method:

  • This method is executed after the request reaches the target resource or the controller execution is completed, provided that the return value of the boolean preHandle() method is true.

void afterCompletion method:

  • This method is executed after the server renders the page, provided that the return value of the boolean preHandle() method is true.

//util类
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从session中 取出 登录用户
        Object user = request.getSession().getAttribute("loginUser");
        if(user!=null){
            return true;
        }
        /**重定向到 登录页面 */
        response.sendRedirect("/login.html?info=noland");
        return false;
    }
}

 2. Register the interceptor class and rewrite the addInterceptors method

//config类
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
//注册自定义拦截器
       registry.addInterceptor(new LoginInterceptor())
//路径匹配 受限资源拦截范围  访问该范围资源就会被拦截(可以写多个)
               .addPathPatterns("/index.html");
    }
}

3. Display interception information on the login page

window.onload = function () {
    let info = getQuery("info");
    if(info=="noland"){
        $("infoDiv").innerHTML = "请先登录";
    }
}

Guess you like

Origin blog.csdn.net/m0_74421344/article/details/130477776