首页IT科技springboot拦截器不生效(spring boot 拦截器)

springboot拦截器不生效(spring boot 拦截器)

时间2025-04-28 21:25:17分类IT科技浏览3494
导读:spring boot 使用拦截器...

spring boot 使用拦截器

1.创建拦截器类            ,继承HandlerInterceptor

2.注册拦截器              ,指定拦截规则

spring framework 中的拦截器类需要继承与HandlerInterceptor,spring boot也是一致的

package com.tons.intercept; import lombok.extern.slf4j.Slf4j; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Slf4j public class RecordIntercept implements HandlerInterceptor { /* request 请求对象 response 响应对象 handler 请求处理器     ,可以强转成HandlerMethod使用(可获取处理方法的相关信息)        。 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 获取路由 String remoteAddr = request.getRemoteAddr(); // 获取访问路径 http:localhost:80/ 后面的url部分 String url = request.getRequestURI(); // 打印 log.debug("{}访问了[{}]",remoteAddr,url); // 返回true 放行,false不放行 return true; } }

注册拦截器         ,指定拦截规则

package com.tons.config; import com.tons.intercept.PowerIntercept; import com.tons.intercept.RecordIntercept; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.Arrays; import java.util.List; /** * 配置拦截器 */ @Configuration public class InterceptConfig implements WebMvcConfigurer { private static final List<String> STATIC_PATH = Arrays.asList("/","/index","/css/**","/js/**","/img/**","/media/**","/vendors/**","/element-ui/**","/temp/**","/public/**","/json/**","/favicon.ico","/error"); /** * 配置拦截器 * @param registry 拦截器 */ @Override public void addInterceptors(InterceptorRegistry registry) { WebMvcConfigurer.super.addInterceptors(registry); //addPathPatterns 拦截路径 //excludePathPatterns 不拦截路径 // /**代表当前目录下所有资源(包含其内部子资源) registry.addInterceptor(new RecordIntercept()).addPathPatterns("/**").excludePathPatterns(STATIC_PATH); } }

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
电脑进入睡眠自动唤醒(电脑自动进入睡眠状态) win10运行vbs(Win11开启VBS功能将严重影响游戏体验 游戏帧率最多下降28%)