SpringBoot(8) SpringBoot过滤器Filter
1、SpringBoot启动默认加载的Filter
characterEncodingFilter
hiddenHttpMethodFilter
httpPutFormContentFilter
requestContextFilter
2、Filter优先级(Ordered.HIGHEST_PRECEDENCE Ordered.LOWEST_PRECEDENCE)
低位值意味着更高的优先级 Higher values are interpreted as lower priority
自定义Filter,避免和默认的Filter优先级一样,不然会冲突
3、自定义Filter
1)使用Servlet3.0的注解进行配置
2)启动类里面增加 @ServletComponentScan,进行扫描
3)新建一个Filter类,implements Filter,并实现对应的接口
4) @WebFilter 标记一个类为filter,被spring进行扫描,urlPatterns:拦截规则,支持正则
5)控制chain.doFilter的方法的调用,来实现是否通过放行 不放行,web应用resp.sendRedirect("/index.html");
场景:权限控制、用户登录(非前端后端分离场景)等
1 @WebFilter(urlPatterns = "/api/*", filterName = "loginFilter") 2 public class LoginFilter implements Filter{ 3 4 5 6 /** 7 * 容器加载的时候调用 8 */ 9 @Override 10 public void init(FilterConfig filterConfig) throws ServletException { 11 System.out.println("init loginFilter"); 12 } 13 14 15 /** 16 * 请求被拦截的时候进行调用 17 */ 18 @Override 19 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 20 System.out.println("doFilter loginFilter"); 21 22 HttpServletRequest req = (HttpServletRequest) servletRequest; 23 HttpServletResponse resp = (HttpServletResponse) servletResponse; 24 String username = req.getParameter("username"); 25 26 if ("admin".equals(username)) { 27 filterChain.doFilter(servletRequest,servletResponse); 28 } else { 29 resp.sendRedirect("/index.html"); 30 return; 31 } 32 33 } 34 35 /** 36 * 容器被销毁的时候被调用 37 */ 38 @Override 39 public void destroy() { 40 System.out.println("destroy loginFilter"); 41 } 42 43 }
启动日志里,已经启动默认加载的Filter和自定义的Filter
官网地址:https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-embedded-container-servlets-filters-listeners