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