方式一
- 创建过滤器实现类实现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);
}
}
- 在springBoot入口类配置
@ServletComponentScan
注解
方式二
- 创建一个普通的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);
}
}
- 创建过滤器核心配置类。
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean<UserFilter> filter = new FilterRegistrationBean<>(new UserFilter());
filter.addUrlPatterns("/user");
return filter;
}
}