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); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端