Spring 自定义过滤器用于在发送回客户端之前过滤响应



我是 Spring 引导过滤器的新手

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

例如GetProductImpl将给出以下响应:

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

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

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

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

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

谢谢。

我目前使用过滤器的方法似乎碰壁了,因为我使用 addFilter、addFilterBefore 甚至 addFilterAfter,所有这些都需要有我不知道它是什么的 out filter 类,并专注于 Web 安全的东西(用户名密码身份验证过滤器::class.java(。

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

通过实现过滤器接口@Add自定义过滤器类。重写执行筛选器方法以修改响应。

定义 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();
}
}

最新更新