Loading

SpringBoot过滤器

方式一

  1. 创建过滤器实现类实现Filter接口。并添加@WebFilter注解。
@WebFilter(urlPatterns = {"/student"})
public class StudentFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器执行...");
        String username = servletRequest.getParameter("username");
        if(username.contains("sb")){
            username = username.replaceAll("sb","*");
        }
        System.out.println(username);
        servletRequest.setAttribute("username",username);
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
  1. 在springBoot入口类配置@ServletComponentScan注解

方式二

  1. 创建一个普通的Filter实现类,不添@WebFilter注解。
public class UserFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器执行...");
        String username = servletRequest.getParameter("username");
        if(username.contains("sb")){
            username = username.replaceAll("sb","*");
        }
        System.out.println(username);
        servletRequest.setAttribute("username",username);
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
  1. 创建过滤器核心配置类。
@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean filterRegistrationBean(){
        FilterRegistrationBean<UserFilter> filter = new FilterRegistrationBean<>(new UserFilter());
        filter.addUrlPatterns("/user");
        return filter;
    }
}
posted @ 2021-09-06 10:56  IamHzc  阅读(418)  评论(0编辑  收藏  举报