springboot过滤器实现
时间: 2023-12-29 10:26:44 浏览: 84
在Spring Boot中,可以通过实现过滤器来实现对请求和响应的处理。以下是一个使用FilterRegistrationBean注册过滤器的示例:
```java
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Configuration
public class MyFilterConfig {
@Bean
public FilterRegistrationBean<MyFilter> myFilter() {
FilterRegistrationBean<MyFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new MyFilter());
registrationBean.addUrlPatterns("/*"); // 设置过滤器的URL模式
return registrationBean;
}
private static class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
// 在这里可以对请求和响应进行处理
// 例如,可以在请求头中添加一些自定义信息
request.addHeader("X-Custom-Header", "Hello");
// 继续调用下一个过滤器或目标资源
filterChain.doFilter(request, response);
}
}
}
```
上述示例中,我们创建了一个名为`MyFilter`的过滤器,并使用`FilterRegistrationBean`将其注册到Spring Boot应用程序中。在`doFilter`方法中,我们可以对请求和响应进行自定义处理,然后调用`filterChain.doFilter`方法继续调用下一个过滤器或目标资源。
阅读全文