跳到主要内容
版本:5.0.1

ModifyResponseBody 过滤器

DeepSeek V3 中英对照 ModifyResponseBody Filter ModifyResponseBody Filter

你可以使用 ModifyResponseBody 过滤器在响应体发送回客户端之前对其进行修改。

备注

此过滤器只能通过 Java DSL 进行配置。

以下清单展示了如何修改响应体过滤器:

import static org.springframework.cloud.gateway.server.mvc.filter.AfterFilterFunctions.modifyResponseBody;
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri;
import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route;
import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http;

@Bean
public RouterFunction<ServerResponse> gatewayRouterFunctionsModifyResponseBodySimple() {
return route("modify_response_body")
.GET("/anything/modifyresponsebody", http())
.before(uri("https://example.org"))
.after(modifyResponseBody(String.class, String.class, null,
(request, response, s) -> s.replace("fooval", "FOOVAL")))
.build();
}

上面的示例没有改变内容类型或执行任何动态操作。下面的示例改变了内容类型并动态修改了内容。

import static org.springframework.cloud.gateway.server.mvc.filter.AfterFilterFunctions.modifyResponseBody;
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri;
import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route;
import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http;
import static org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates.host;
import org.springframework.http.MediaType;

@Configuration
class RouteConfiguration {

@Bean
public RouterFunction<ServerResponse> gatewayRouterFunctionsModifyResponseBody() {
return route("modify_response_bodu")
.route(host("*.modifyresponsebodu.org"), http())
.before(uri("https://example.org"))
.after(modifyResponseBody(String.class, String.class, MediaType.APPLICATION_JSON_VALUE,
(request, s) -> s.toUpperCase()))
.build();
}

}