1. springboot WebAppConfig配置
/**
* Created with IntelliJ IDEA.
*
* @author: zhangenke @Date: 2018/8/16 on 下午2:25
* @description: 让 springBoot 知道有这个拦截器
*/
@Slf4j
@Configuration
public class WebAppConfig extends WebMvcConfigurationSupport {
// 以下WebMvcConfigurerAdapter 比较常用的重写接口
// /** 解决跨域问题 **/
// public void addCorsMappings(CorsRegistry registry) ;
// /** 添加拦截器 **/
// void addInterceptors(InterceptorRegistry registry);
// /** 这里配置视图解析器 **/
// /** 视图跳转控制器 **/
// void addViewControllers(ViewControllerRegistry registry);
// void configureViewResolvers(ViewResolverRegistry registry);
// /** 配置内容裁决的一些选项 **/
// void configureContentNegotiation(ContentNegotiationConfigurer configurer);
// /** 视图跳转控制器 **/
// void addViewControllers(ViewControllerRegistry registry);
// /** 静态资源处理 **/
// void addResourceHandlers(ResourceHandlerRegistry registry);
// /** 默认静态资源处理器 **/
// void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer);
// private final ProcureInterceptor procureInterceptor;
//
// @Autowired
// public WebAppConfig(ProcureInterceptor procureInterceptor) {
// this.procureInterceptor = procureInterceptor;
// }
private final TokenUtils tokenUtils;
private final TokenDao tokenDaoImpl;
@Autowired
public WebAppConfig(TokenUtils tokenUtils, TokenDao tokenDaoImpl) {
this.tokenUtils = tokenUtils;
this.tokenDaoImpl = tokenDaoImpl;
}
@Bean
public ProcureInterceptor getProcureInterceptor() {
return new ProcureInterceptor(tokenUtils, tokenDaoImpl);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 多个拦截器组成一个拦截器链
// addPathPatterns 用于添加拦截规则
// excludePathPatterns 用户排除拦截
log.info("tokenUtils:{}", tokenUtils);
log.info("tokenDaoImpl:{}", tokenDaoImpl);
log.info("WebAppConfig拦截器注入成功:**********************************************");
// log.info("procureInterceptor:{}", procureInterceptor);
// registry.addInterceptor(new ProcureInterceptor(tokenUtils,
// tokenDaoImpl)).addPathPatterns("/**")
registry
.addInterceptor(getProcureInterceptor())
.addPathPatterns("/**")
.excludePathPatterns(
"/swagger-resources/**",
"/webjars/**",
"/v2/**",
"/swagger-ui.html/**",
"/configuration/**");
// 对来自/user/** 这个链接来的请求进行拦截;
// super.addInterceptors(registry);
// registry.addInterceptor(getInterfaceAuthCheckInterceptor()
// 这种方式无论什么情况都可以
// registry.addInterceptor(new InterfaceAuthCheckInterceptor())
// 这种情况时,自定义的interceptor中不能注入其他内容,比如redis或者其他service,如果要注入,必须使用上面这种方法
}
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry
.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
/**
* @param [configurer]
* @return void
* @author chaosgod 2018/10/17 上午11:34
* @description : 配置访问静态文件
*/
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Override
public void configureMessageConverters(List> converters) {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullBooleanAsFalse,
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.PrettyFormat,
SerializerFeature.DisableCircularReferenceDetect);
converter.setFastJsonConfig(config);
converters.add(converter);
// SerializerFeature.WriteNullListAsEmpty:List类型字段为null时输出[]而非null
// SerializerFeature.WriteMapNullValue:显示空字段
// SerializerFeature.WriteNullStringAsEmpty:字符串类型字段为null时输出""而非null
// SerializerFeature.WriteNullBooleanAsFalse:Boolean类型字段为null时输出false而null
// SerializerFeature.PrettyFormat:美化json输出,否则会作为整行输出
}
// @Override
// protected void addCorsMappings(CorsRegistry registry) {
// registry.addMapping("/**");
// super.addCorsMappings(registry);
// }
}
2. ProcureInterceptor配置
/**
* @author zhangenke
*/
@Slf4j
@Component
public class ProcureInterceptor implements HandlerInterceptor {
private static final String VALUE = "false";
private static final String OPTIONS = "OPTIONS";
private final SessionService sessionServiceImpl;
@Autowired
public ProcureInterceptor(SessionService sessionServiceImpl) {
this.sessionServiceImpl = sessionServiceImpl;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String[] noFilters = new String[]{"login", "errorSession", "swagger", "images", "v2"};
String uri = request.getRequestURI();
boolean beFilter = true;
log.info("请求地址uri:{}", uri);
log.info("请求方式:{}", request.getMethod());
// 预请求
if (OPTIONS.equals(request.getMethod())) {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Authentication,Origin, X-Requested-With, " +
"Content-Type, Accept,sessionId");
return true;
}
// 配置跨域
response.setHeader("Access-Control-Allow-Origin", "*");
String requestId = request.getHeader("X-REQUEST-ID");
String userAgent = request.getHeader("User-Agent");
if (requestId != null) {
MDC.put("requestUUID", requestId);
}
if (userAgent != null) {
MDC.put("User-Agent", userAgent);
}
log.info("变量:{}", JSON.toJSONString(request.getParameterMap()));
String sessionId = request.getHeader("sessionId");
log.info("Headers-sessionId: {}", sessionId);
for (String s : noFilters) {
if (uri.contains(s)) {
beFilter = false;
break;
}
}
String origin = request.getHeader("Origin");
log.info("请求收到的Origin为:{}", origin);
// todo
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception
ex) {
// TODO Auto-generated method stub
}
}
如上图,这样配置即可,
2018-10-23优化,亲测可过swagger-ui,及静态文件
2019-01-22优化,本地测试可随意过,上线Linux,会偶尔出现跨域,但重新打包后,又可以过。
目前,暂未找到该问题的解决办法
(可能与Linux有关,杀掉进程后,如果Enter直到出现此进程被杀的提示后,重新上线,即可过)