SpringBoot(8) SpringBoot过滤器Filter

时间:2021-12-06 17:56:46

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");

场景:权限控制、用户登录(非前端后端分离场景)等

 @WebFilter(urlPatterns = "/api/*", filterName = "loginFilter")
public class LoginFilter implements Filter{ /**
* 容器加载的时候调用
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("init loginFilter");
} /**
* 请求被拦截的时候进行调用
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("doFilter loginFilter"); HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse resp = (HttpServletResponse) servletResponse;
String username = req.getParameter("username"); if ("admin".equals(username)) {
filterChain.doFilter(servletRequest,servletResponse);
} else {
resp.sendRedirect("/index.html");
return;
} } /**
* 容器被销毁的时候被调用
*/
@Override
public void destroy() {
System.out.println("destroy loginFilter");
} }

SpringBoot(8) SpringBoot过滤器Filter

启动日志里,已经启动默认加载的Filter和自定义的Filter

官网地址:https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-embedded-container-servlets-filters-listeners