spring boot 拦截器不生效的原因
spring boot 拦截器不生效的原因
没加@Component或者@Configuration注解
@ComponentScan没扫描到
如果启动类和拦截类在平级或者拦截类父级平级的情况下,ComponentScan一般都会扫描到,除非启动类中指定了;
路径配置错了
拦截器的路径配置错误,类不在范围;
已经有类集成了拦截类
项目中有类已经集成了 WebMvcConfigurationSupport 或 WebMvcConfigurerAdapter 或 WebMvcConfigurer 你再定集成这些类也不会生效;
其中资源访问配置类,swagger等配置都会使用WebMvcConfigurer来配置,需要把这些类整合在一个类中就可以了;
登录验证DEMO:
拦截配置类:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class ResourceConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //可以访问localhost:8095/static/images/image.jpg registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new AccessInterceptor()) .addPathPatterns("/**") .excludePathPatterns("/sys/login"); } }
自定义拦截器:
import cn.dev33.satoken.stp.StpUtil; import com.ajr.alllink.util.ResponseMessage; import com.ajr.alllink.util.ResponseMsgEnum; import com.ajr.alllink.util.Result; import com.alibaba.fastjson.JSONObject; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class AccessInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Boolean boo = StpUtil.isLogin(); System.out.println("全局拦截器 是否登录: "+boo); // 未登录 if(!boo){ ResponseMessage error = Result.error(ResponseMsgEnum.TOKEN_ERROR.getCode()); String json = JSONObject.toJSONString(error); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); PrintWriter out = null; try { out = response.getWriter(); out.append(json); System.out.println("全局拦截器 返回数据: "+json); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } } return false; } //将memberId传入,其他方法通过request.getAttribute("memberId")接收 request.setAttribute("memberId", request.getHeader("memberId")); return true; } }
除了/sys/login接口不需要登录外,其他接口都需要登录;