篇首语:本文由编程笔记#自由互联小编为大家整理,主要介绍了拦截过滤器相关的知识,希望对你有一定的参考价值。
一简介
二编码
1.注入bean启动Configuration程序
Slf4jConfigurationpublic 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("/**"); }}
Slf4jComponentpublic class AuthFilter implements HandlerInterceptor { /**不需要验证接口**/ String [] urls {}; List 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 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; charsetutf-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 { }}【文章出处:香港cn2服务器 http://www.558idc.com/st.html 复制请保留原URL】