SpringBoot拦截器的设置

1.登录拦截实现HandlerInterceptor接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class LoginInterceptor implements HandlerInterceptor {
    /**
     *
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 处理器(url+controller),映射
     * @return 返回值为true,放行请求;返回值为false,拦截当前请求
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
 
        User user = (User) request.getSession().getAttribute("user");
        // 用户没有登陆过
        if(null == user){
            response.sendRedirect("/web/login.html");
            return false;
        }
 
        return true;
    }
}

2.定义配置类取实现WebMvcConfigurer 接口,重写addInterceptors方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 加载当前的拦截器并进行注册
@Configuration
public class MyAppConfig implements WebMvcConfigurer {
    /**
     * 拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 创建拦截器对象
        HandlerInterceptor handlerInterceptor = new LoginInterceptor();
 
        // 白名单
        List<String> excludePath = new ArrayList<>();
        excludePath.add("/bootstrap3/**");
        excludePath.add("/css/**");
        excludePath.add("/images/**");
        excludePath.add("/js/**");
        excludePath.add("/web/register.html");
        excludePath.add("/web/login.html");
        excludePath.add("/web/product.html");
        excludePath.add("/users/login");
        excludePath.add("/users/register");
        excludePath.add("/index.html");
 
        registry.addInterceptor(handlerInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(excludePath);
    }
 
}

posted on   玄凰寒  阅读(177)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示