SpringBoot中快速开发一个过滤器Filter
一:写一个类实现Filter接口,重写doFilter方法
要注意:如果想从request和response中做一些事情,请进行类型转换
1 /**
*使用@WebFilter注解的方式只能根据过滤器名的类名顺序执行,添加@Order注解是无效的, 5 * 因为@WebFilter在容器加载时,不会使用@Order注解定义的顺序,而是默认直接使用类名排序 6 */ 7 @WebFilter(urlPatterns = {"/service/*"}, filterName = "AAuthFilter") 8 public class AAuthFilter implements Filter { 9 @Override 10 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
11 HttpServletRequest request = (HttpServletRequest) servletRequest; 12 HttpServletResponse response = (HttpServletResponse) servletResponse; 13 String auth_token = request.getHeader(AUTH_HEAD); 14 boolean verification = JWTUtil.verification(auth_token); 15 if (!verification) { 16 response.setCharacterEncoding("UTF-8"); 17 response.setContentType("application/json; charset=utf-8"); 18 PrintWriter out = response.getWriter(); 19 JSONObject res = new JSONObject(); 20 res.put("msg", "请求被拒绝"); 21 res.put("success", "false"); 22 res.put("code", 401); 23 out.append(res.toString()); 24 out.flush(); 25 return; 26 } 27 28 filterChain.doFilter(servletRequest,servletResponse); 29 } 30 }
二:然后需要在启动类上加上@ServletComponentScan过滤器才会生效
1 //使过滤器生效 2 @ServletComponentScan 3 public class Application { 4 5 public static void main(String[] args) { 6 SpringApplication.run(Application.class,args); 7 } 8 9 }