Spring Boot 响应过滤器 [英] Spring boot Response Filter

查看:52
本文介绍了Spring Boot 响应过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用过 JERSEY 框架,它提供了实现过滤器的功能,以便所有响应都通过它.

I have worked with JERSEY framework , it provides feature to implement a filter so that all the responses will go through it.

我是 Spring/Spring Boot 的新手.我不明白如何实现我提到的上述功能.

I am new to Spring / Spring boot. I am not understanding how to achieve the above functionality which I mentioned.

基本上我希望我的每个响应都应该通过我的过滤器.

Basically I want my each Response should pass through my filter.

如何做到这一点?

示例示例会有所帮助.

如果我按照 @Errabi Ayoub 建议如下实施:

If I implemented as follows as @Errabi Ayoub suggested:

@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(); 然后我的方法将被调用两次,根据我的逻辑,首先它将在请求时调用,然后在响应时再次调用.我不想要那个.我只想在响应时登录.

and I have a method apiLogger.logResponse(); then my method will be called twice, according to my logic, first it will be called at request and then again on response. I don't want that. I want to log only when it is Response.

谢谢.

推荐答案

你可以通过实现 Filter 接口来做到这一点

You can do that by implementing Filter interface

@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 {}

}

这篇关于Spring Boot 响应过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆