Shi*_*ppa 13 spring spring-mvc spring-boot
我曾经使用过 JERSEY 框架,它提供了实现过滤器的功能,以便所有响应都将通过它。
我是 Spring/Spring boot 的新手。我不明白如何实现我提到的上述功能。
基本上我希望我的每个响应都应该通过我的过滤器。
这个怎么做 ?
一个示例将会有所帮助。
如果我按照@Errabi Ayoub建议实施如下:
@Component
public class MyClassFilter implements Filter {
  @Override
  public void doFilter( HttpServletRequest req,  HttpServletResponse res,
      FilterChain chain) throws IOException, ServletException {
       // you can modify your response here before the call of chain method
       //example 
        apiLogger.logResponse();
         res.setHeader("key", "value");
    chain.doFilter(req, res);
  }
  @Override
  public void destroy() {}
  @Override
  public void init(FilterConfig arg0) throws ServletException {}
}
我有一个方法apiLogger.logResponse();,然后我的方法将被调用两次,根据我的逻辑,首先将根据请求调用它,然后根据响应再次调用。我不想要这样。我只想在响应时才记录。
谢谢。
简短的答案是在 doFilter 方法之后过滤响应。
    @Bean
    public Filter myCustomFilter() {
        return (request, response, chain) -> {
            logger.info("do Request Filtering ... ");
            chain.doFilter(request, response); // Do Response Filter after this
            logger.info("do Response Filtering ... ");
        };
    }
解释
Servlet 容器中的 Servlet Filter 在链中被调用,每个 Filter 通过 FilterChain doFilter 方法调用链中的下一个 Filter。过滤器链中的最后一个过滤器将请求委托给实际的 Servlet,然后该 Servlet 处理该请求并生成响应。然后响应通过过滤器链中的每个过滤器,但顺序相反。因此,在处理响应时,最后一个过滤器将成为第一个过滤器,并且它会通过所有过滤器返回客户端。
您可以通过实现 Filter 接口来做到这一点
@Component
public class MyClassFilter implements Filter {
  @Override
  public void doFilter( HttpServletRequest req,  HttpServletResponse res,
      FilterChain chain) throws IOException, ServletException {
       // you can modify your response here before the call of chain method
       //example 
         res.setHeader("key", "value");
    chain.doFilter(req, res);
  }
  @Override
  public void destroy() {}
  @Override
  public void init(FilterConfig arg0) throws ServletException {}
}
| 归档时间: | 
 | 
| 查看次数: | 26717 次 | 
| 最近记录: |