Spring Boot(04)自定义filter

tech2024-05-27  75

第04篇:自定义filter

方案

FilterRegistrationBean bean@WebFilter注解 + @ServletComponentScan

流程

定义filter class配置filter bean

1. filter class

public class MyFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { // System.out.println(filterConfig.getInitParameter("param")); } @Override public void destroy() { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)servletRequest; System.out.println("filter, url: " + request.getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } }

2. filter bean

@Bean public FilterRegistrationBean filterRegistrationBean() { // 新建过滤器注册类 FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setFilter(new MyFilter()); // 设置过滤器的URL模式 registrationBean.addUrlPatterns("/*"); // init params registrationBean.addInitParameter("param", "value"); registrationBean.setName("MyFilter"); //设置过滤器顺序 registrationBean.setOrder(1); return registrationBean; }

注解方案

启动类注解:@ServletComponentScan Filter实现类注解:

@WebFilter(filterName = "Second Filter", urlPatterns = "/*", initParams = { @WebInitParam(name = "author", value = "XX") }) public class MyFilter implements Filter { //... }
最新回复(0)