spring boot 拦截器不生效的原因 - 简书 (jianshu.com)
-
没加@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;
/**
* Created By: hdx
* Date: 2021-04-07 16:53
*/
@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;
/**
* Created By: hdx
* Date: 2021-04-19 14:24
*/
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;
}
return true;
}
}
除了/sys/login接口不需要登录外,其他接口都需要登录;
登录使用的sa-token框架, sa-token 地址:
作者:星野君
链接:https://www.jianshu.com/p/cb897ae2419c
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。