QiYongchuan / MyGitBlog

个人博客主页,记录计算机学习,前端-后端-全栈学习ing
15 stars 0 forks source link

SpringBoot学习笔记:拦截器 #91

Open QiYongchuan opened 3 months ago

QiYongchuan commented 3 months ago

拦截器(Interceptor)是用来拦截进入Controller方法之前或之后的请求的。 它们常用于日志记录、身份验证、权限检查、或者添加通用的请求或响应的头信息等场景。

image

用的最多的是preHandle

简单使用:

1.创建拦截器

public class LoginInterceptor  implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("登录拦截器");
        return true;
         //  其中request对应的就是前端的请求
//        if (request.getSession().getAttribute("user") == null)
//            return false;
//        else if (request.getSession().getAttribute("user") != null) {
//            return true;
//        }   可根据条件来判断
    }
}

2.注册拦截器

@Configuration   //注明是配置类
public class WebConfig implements WebMvcConfigurer {
    @Override     // 添加拦截器,将我们之前写的拦截器注册,添加拦截的路径,使其生效
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/user/**");

        registry.addInterceptor(new LoginInterceptor());  //也可以不添加拦截的路径,这样默认所有的都拦截

        // 拦截之后就是调用LoginInterceptor的preHandle方法
    }
}
QiYongchuan commented 3 months ago

详细介绍

image image