一、添加拦截器
public class PermissionInterceptor extends HandlerInterceptorAdapter {
@Override
//在业务处理器处理请求之前被调用。预处理,可以进行编码、安全控制等处理;
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
//验证权限
checkPermission(handler);
return true;
}
@Override
//在业务处理器处理请求执行完成后,生成视图之前执行。后处理(调用了Service并返回ModelAndView,但未进行页面渲染),有机会修改ModelAndView;
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
@Override
//在DispatcherServlet完全处理完请求后被调用,可用于清理资源等。返回处理(已经渲染了页面),可以根据ex是否为null判断是否发生了异常,进行日志记录;
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
@Override
public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
}
/**
* 是否有权限
*
* @param handler
* @return
*/
private void checkPermission(Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
// 获取方法上的注解
//allowAnonymous不加任何验证
AllowAnonymous allowAnonymous = handlerMethod.getMethod().getAnnotation(AllowAnonymous.class);
if (allowAnonymous != null)
return;
RequiredPermission requiredPermission = handlerMethod.getMethod().getAnnotation(RequiredPermission.class);
// 如果方法上的注解为空 则获取类的注解
if (requiredPermission == null) {
requiredPermission = handlerMethod.getMethod().getDeclaringClass().getAnnotation(RequiredPermission.class);
}
// 如果标记了注解,则判断权限
if (requiredPermission != null) {
//TODO
}
}
}
}
一、添加拦截器
/**
* web 配置文件
*/
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
/**
* 跨域支持
*/
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4
FilterRegistrationBean bean = new FilterRegistrationBean<>(new CorsFilter(source));
// 这个顺序很重要哦,为避免麻烦请设置在最前
bean.setOrder(0);
return bean;
}
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
corsConfiguration.addAllowedHeader("*"); // 2允许任何头
corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等)
return corsConfiguration;
}
/**
* 添加静态资源--过滤swagger-api (开源的在线API文档)
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 过滤swagger,addResourceLocations指的是文件放置的目录,addResoureHandler指的是对外暴露的访问路径
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
// 第一个方法设置访问路径前缀,第二个方法设置资源路径
registry.addResourceHandler("/**").addResourceLocations("classpath:/public/");
//要加file
//registry.addResourceHandler("/img/**").addResourceLocations("file:E:/GitRepository/ikang-tech/tech-service/imgs/");
registry.addResourceHandler("/img/**").addResourceLocations("file:"+projectPath.getImgPath());
}
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
return factory -> {
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");
factory.addErrorPages(error404Page);
};
}
@Bean
public PermissionInterceptor getLoginInterceptor(){
return new PermissionInterceptor(authService);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getLoginInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/error")
.excludePathPatterns("/static/*")
.excludePathPatterns("/auth/*")
.excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
}
}