1、新增过滤器
(1)配置
@WebFilter(filterName = "corsFilter")
public class CorsFilter extends OncePerRequestFilter {@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {response.setHeader("Access-Control-Allow-Origin", "*");response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");response.setHeader("Access-Control-Max-Age", "3600");response.setHeader("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,X-Auth-Token");chain.doFilter(request, response);}
}
(2)在启动类中声名,启动过滤器
@Bean
public FilterRegistrationBean indexFilterRegistration(){FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new CorsFilter());filterRegistrationBean.addUrlPatterns("/*");return filterRegistrationBean;
}
2、集成Swagger
(1)新增配置
@Configuration @EnableSwagger2 public class SwaggerConfig {@Beanpublic Docket userApi() {return new Docket(DocumentationType.SWAGGER_2).select() // 选择那些路径和api会生成document.apis(RequestHandlerSelectors.basePackage("controller层地址")).paths(PathSelectors.any()) // 对所有路径进行监控 .build().apiInfo(userInfo());}private ApiInfo userInfo() {return new ApiInfoBuilder().title("测试").description("测试").version("1.0.0").license("").build();}
(2)在启动类上新加声名
@EnableCaching
@EnableSwagger2
3、线程池配置
@Configuration public class ThreadPoolConfig {@BeanThreadPoolExecutorFactoryBean executorServiceFactory() {ThreadPoolExecutorFactoryBean factory = new ThreadPoolExecutorFactoryBean();factory.setThreadNamePrefix("query");factory.setMaxPoolSize(100);factory.setCorePoolSize(20);factory.setQueueCapacity(10000);return factory;}@Primary@BeanExecutorService executorService() throws Exception {return executorServiceFactory().getObject();} }
4、拦截器
@Configuration @EnableWebMvc @ComponentScan public class WebConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {private ApplicationContext applicationContext;@AutowiredAuthControl authControl;public WebConfig(){super();}@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");super.addResourceHandlers(registry);}@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext = applicationContext;}@Overridepublic void addInterceptors(InterceptorRegistry registry) {//登录拦截规则:除了login,其他都拦截判断/swagger-resources/configuration/uiregistry.addInterceptor(authControl).addPathPatterns("/**").excludePathPatterns("/user/login/**","/user/notice/index","/user/info/noticeDetail","/swagger-ui.html","/configuration/**","/swagger-resources/**","/v2/**","/headLine/**","/es/**","/**/*.js","/**/*.css","/**/*.svg","/**/*.ttf","/**/*.woff","/**/*.woff2","/**/*.png","/**/*.jpg","/**/*.gif");super.addInterceptors(registry);}}
@Component
public class AuthControl extends HandlerInterceptorAdapter {
@Autowired
private AdminProperties props;
@Autowired
private TokenManager tokenManager;
@Autowired
private UserService userService;
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
if (!props.isEnableAuthControl()) {
initTestData();
return true;
}
URI uri;
try {
uri = new URI(request.getRequestURI());
} catch (URISyntaxException e) {
throw new ServletException(e);
}
try {
CheckResult result = checkAuthority(request, uri.getPath());
if (result.getResult()) {
return true;
}
unauthorized(response, result.getErrorMsg());
} catch (Exception e) {
throw new ServletException(e);
}
return false;
}
private void unauthorized(HttpServletResponse response, String msg) throws IOException {
ObjectMapper om = new ObjectMapper();
response.getWriter().write(om.writeValueAsString(ResponseUtil.error(msg ==null ? "token登录失效" : msg)));
}
private CheckResult checkAuthority(HttpServletRequest request, String path) throws NoSuchAlgorithmException, java.security.SignatureException, InvalidKeySpecException {
CheckResult checkResult = new CheckResult();
// 1.验证X-Auth-Token
String tokenStr = request.getHeader("X-Auth-Token");
if (tokenStr == null) {
return checkResult.setErrorMsg("认证失败,缺少X-Auth-Token");
}
Token token;
try {
token = tokenManager.decodeTerminalToken(tokenStr);
...
...
...
} catch (ExpiredJwtException e) {
return checkResult.setErrorMsg("认证失败,token已过期,请重新登录");
} catch (SignatureException e) {
return checkResult.setErrorMsg("认证失败,非法的token");
} catch (Exception e) {
return checkResult.setErrorMsg("执行失败");
}
return checkResult.setResult(true);
}
5、redis配置
@Configuration public class RedisConfig {@Autowiredprivate RedisTemplate redisTemplate;@Beanpublic RedisTemplate redisTemplateInit(){//设置序列化key的实例化对象redisTemplate.setKeySerializer(new StringRedisSerializer());//设置序列化value的实例化对象redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());redisTemplate.setHashKeySerializer(new StringRedisSerializer());redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());return redisTemplate;}}