在工作中除了通过过滤器配置校验,拦截器配置校验规则也是很常见方式,这里通过WebMvcConfigurer 和 HandlerInterceptor 拦截器配置校验。
1、配置拦截器(这个里面添加了跨域支持,当集成swagger防止后台报错),如果没有必要删除其配置,这里做一下展示。
@Configuration
public class AdminCommonConfig implements WebMvcConfigurer {
/**
* 跨域支持
* @param registry
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600 * 24);
}
/**
* 自定义拦截器地址
* @return
*/
@Bean
public HandlerInterceptor authInterceptor(){
return new AuthInterceptor();
}
/**
* 添加拦截路径
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
String url = "/**";
//添加排除排除URL校验路径
registry.addInterceptor(authInterceptor()).addPathPatterns(url).excludePathPatterns(
"/test/exclude/*"
);
}
/**
* 当集成swagger防止后台报错
* No mapping found for HTTP request with URI [/swagger-resources/configuration/ui] in DispatcherServlet with name 'dispatcherServlet'
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//过滤swagger
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
2、添加在WebMvcConfigurer 中配置HandlerInterceptor
public class AuthInterceptor implements HandlerInterceptor {
/**
* 通过配置是否认证,对开发环境免除校验,方便开发
*/
@Value("${is.auth}")
private boolean isAuth;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if(handler instanceof HandlerMethod){
//可以从handler 获取中获得方法
// Method method = ((HandlerMethod) handler).getMethod();
if(isAuth){
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request1 = requestAttributes.getRequest();
String sign = request1.getHeader("sign");
System.out.println("从HttpServletRequest直接获取"+sign);
String sign1 = request1.getHeader("sign");
System.out.println("从RequestContextHolder中获取的"+sign1);
if ("123".equals(sign1)) {
System.out.println("校验通过");
return true;
}
System.out.println("校验不通过");
return false;
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}