OncePerRequestFilter 和GenericFilterBean 区别
时间: 2023-12-19 08:32:15 浏览: 198
OncePerRequestFilter和GenericFilterBean都是Spring框架中的过滤器类,它们的区别如下:
1.继承关系不同:OncePerRequestFilter继承自GenericFilterBean,而GenericFilterBean实现了Filter接口。
2.执行次数不同:OncePerRequestFilter保证在一次请求中只会被执行一次,而GenericFilterBean在每次请求时都会被执行。
3.方法不同:OncePerRequestFilter中重写的是doFilterInternal方法,而GenericFilterBean中重写的是doFilter方法。
下面是一个OncePerRequestFilter的例子,用于在请求头中添加一个自定义的token:
```java
public class TokenFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String token = "myToken";
response.addHeader("token", token);
filterChain.doFilter(request, response);
}
}
```
下面是一个GenericFilterBean的例子,用于在请求头中添加一个自定义的header:
```java
public class HeaderFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.addHeader("myHeader", "myValue");
chain.doFilter(request, response);
}
}
```
阅读全文