springboot配置过滤器
时间: 2023-10-14 09:11:37 浏览: 60
Spring Boot中使用过滤器可以通过实现Filter接口来实现,也可以通过注解@WebFilter来实现。下面分别介绍这两种方式的实现方式。
1. 实现Filter接口
首先创建一个过滤器类,实现Filter接口:
```
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("过滤器初始化");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("执行过滤操作");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
System.out.println("过滤器销毁");
}
}
```
然后在Spring Boot的配置类中将该过滤器加入到过滤器链中:
```
@Configuration
public class WebConfig {
@Bean
public FilterRegistrationBean<MyFilter> filterRegistrationBean() {
FilterRegistrationBean<MyFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new MyFilter());
registrationBean.addUrlPatterns("/*");
registrationBean.setName("MyFilter");
registrationBean.setOrder(1);
return registrationBean;
}
}
```
2. 使用@WebFilter注解
直接在过滤器类上加上@WebFilter注解即可:
```
@WebFilter(filterName = "MyFilter", urlPatterns = "/*")
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("过滤器初始化");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("执行过滤操作");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
System.out.println("过滤器销毁");
}
}
```
阅读全文