【问题标题】:Spring Custom Filter to filter response before sending back to clientSpring Custom Filter 在发送回客户端之前过滤响应
【发布时间】:2018-10-03 07:06:51
【问题描述】:

我是 Spring Boot 过滤器的新手

我需要将 servlet(impl) 产生的响应修改为某种模式。

例如, GetProductImpl 会给出

的响应
{
      "id": 72167,
      "merchantId": 3,
      "amount": 1,
      "state": "Unused"
}

所以在它发送回客户端之前,我需要将其修改为(将响应放在 module 下)(对于所有 servlet 的所有响应)

{
"module":[{
      "id": 72167,
      "merchantId": 3,
      "amount": 1,
      "state": "Unused"
    }],
"success":true,
"errorCode":null,
"notSuccess":false
}

我正在寻找任何可以让我这样做的方法,因为在 impl 中这样做是没有意义的,因为如果那样的话,我需要为所有 impl 这样做(这很多而且不可行)。

如果有人有任何其他方法可以实现这一点也可以,因为我不知道采取什么方法来做到这一点(java示例也可以)。

谢谢。

我目前使用过滤器的方法似乎碰壁了,因为我使用 addFilter、addFilterBefore 甚至 addFilterAfter,它们都需要有 out 过滤器类,我不知道它是什么,并专注于网络安全的东西(UsernamePasswordAuthenticationFilter::class.java).

.addFilterBefore(JWTAuthenticationFilter(tokenAuthenticationService, objectMapper), UsernamePasswordAuthenticationFilter::class.java)

【问题讨论】:

标签: java spring servlets filter kotlin


【解决方案1】:

@通过实现过滤器接口添加自定义过滤器类。覆盖 do filter 方法以修改您的响应。

如果你使用多个过滤器,定义一个bean的@Component注解和@Order注解来标记过滤器执行的执行顺序。

@Component
@Order(1)
public class CustomFilter implements Filter {

  @Override
    public void doFilter(
      ServletRequest request, 
      ServletResponse response, 
      FilterChain chain) throws IOException, ServletException {

  HttpServletRequest req = (HttpServletRequest) request;
  HttpServletResponse res = (HttpServletResponse) response;
  chain.doFilter(request, response);
        // Modify your response  
        res.getContentType();
    }
}

【讨论】:

  • 这个过滤器在从客户端 -> 服务器发送请求时执行,而不是相反。
猜你喜欢
  • 2020-08-01
  • 2022-11-04
  • 1970-01-01
  • 2020-02-29
  • 1970-01-01
  • 1970-01-01
  • 2022-11-23
  • 1970-01-01
  • 2014-10-01
相关资源
最近更新 更多