一:简介
- 拦截过滤器模式(Intercepting Filter Pattern)用于对应用程序的请求或响应做一些预处理/后处理。定义过滤器,并在把请求传给实际目标应用程序之前应用在请求上。过滤器可以做认证/授权/记录日志,或者跟踪请求,然后把请求传给相应的处理程序。以下是这种设计模式的实体
二:编码
1.注入bean,启动@Configuration程序
@Slf4j
@Configuration
public class BeanConfiguration implements WebMvcConfigurer {
/**
* @Author: guwenhai
* @Description: 拦截器
* @Date: 2021-03-24 19:24
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 添加拦截器,可添加多个
// addPathPatterns("/**") 设置拦截哪些请求,/** 拦截所有请求
registry.addInterceptor(new AuthFilter()).addPathPatterns("/**");
}
}
- 实现拦截器
@Slf4j
@Component
public class AuthFilter implements HandlerInterceptor {
/**不需要验证接口**/
String [] urls = {};
List<String> url = Arrays.asList(urls);
/**
* @Author: guwenhai
* @Description: 在业务处理器处理请求之前被调用
* 如果返回true 执行下一个拦截器,直到所有的拦截器都执行完毕 再执行被拦截的Controller。
* 如果返回false 从当前的拦截器往回执行所有拦截器的afterCompletion(),再退
* @Date: 2021-03-24 19:17
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String uri = request.getRequestURI();
try {
List<String> collect = url.stream().filter(t -> uri.indexOf(t) >= 0).collect(Collectors.toList());
// 如果是不拦截的请求,则允许访问
int bool = 1;
if(collect.size() > 0){
bool = 2;
}
if(bool == 1){
}
return true;
} catch (Exception e) {
log.error(e.getMessage());
log.error("过滤拦截器异常");
e.fillInStackTrace();
returnJson(response,"{\"code\":"+StatusCode.intercept.getCode()+",\"msg\":\""+StatusCode.intercept.getMsg()+"\"}");
return false;
}
}
/**
* @Author: guwenhai
* @Description: 返回客户端数据
* @Date: 2021-03-25 16:18
*/
private void returnJson(HttpServletResponse response, String json) throws Exception{
PrintWriter writer = null;
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=utf-8");
try {
writer = response.getWriter();
writer.print(json);
} catch (IOException e) {
} finally {
if (writer != null)
writer.close();
}
}
/**
* @Author: guwenhai
* @Description: 在业务处理器处理请求执行完成后,生成视图之前执行的动作
* @Date: 2021-03-24 19:19
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
/**
* @Author: guwenhai
* @Description: 完全处理完请求后被调用
* @Date: 2021-03-24 19:19
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}