配置文件中添加拦截器要拦截和要放过
interceptor:
#拦截所有以api开头的请求 多个就用逗号隔开
path-patterns: /api/**,/user/**
#放过这个请求
exclude-path-patterns: /api/page/m
然后写一个拦截器类 ,主要重写第一个方法,做一下判断
/**
* 内部调用接口拦截
*
* @author linnine
*/
@Slf4j
@Component
public class ApiInterceptor implements HandlerInterceptor {
/**
* 判断是否为内网访问
* @param request
* @param response
* @param handler
* @return
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
if( ...判断条件,成功就通过)){
return true;
}
log.info("判断不可通过,进行拦截,输出json");
ServletOutputStream outputStream = response.getOutputStream();
String resp = JsonUtil.toJsonStr(Result.failed(BizCode.PERMISSION_CHECK_FAILURE));
outputStream.write(resp.getBytes());
outputStream.flush();
outputStream.close();
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
写完拦截器,到拦截器配置类中添加
/**
* 拦截器配置类
*
* @author : linnine09
* @date : 2022-03-30
*/
@Slf4j
@Configuration
@RequiredArgsConstructor
@RefreshScope
public class InterceptorConfig extends WebMvcConfigurationSupport {
@Value("${interceptor.path-patterns}")
private String[] pathPatterns;
@Value("${interceptor.exclude-path-patterns}")
private String[] excludePathPatterns;
@Resource
private ApiInterceptor apiInterceptor;
@Override
protected void addInterceptors(InterceptorRegistry registry) {
log.info("pathPatterns={}", JsonUtil.toJsonStr(pathPatterns));
registry.addInterceptor(apiInterceptor).addPathPatterns(pathPatterns)
.excludePathPatterns(excludePathPatterns);
//如果要配置多套,就另起一行
registry.addInterceptor(apiHealthyInterceptor).addPathPatterns("/**");
super.addInterceptors(registry);
}
/**
* 解决swagger-ui.html访问不到问题
*
* @param registry
*/
@Override
protected 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);
}
}