Working with Servlets and Servlet Filters
Spring Cloud Gateway Server MVC 是为基于 Servlet API 且部署到 Servlet 容器的 Servlet 堆栈 Web 应用程序构建的。如果你的应用程序使用 Servlet 或 Servlet 过滤器,你可能需要注意它们的顺序。
Spring Cloud Gateway Server MVC is built for Servlet-stack web applications built on the Servlet API and deployed to Servlet containers. If your applications uses Servlets or Servlet Filters you may need to take care in their ordering.
由于 Servlet 容器处理请求参数的方式,当 Spring WebMVC 应用程序接收到内容类型为 application/x-www-form-urlencoded
时,Servlet 容器会将这些内容与查询参数组合成“请求”参数。Spring Cloud Gateway Server MVC 中包含一个特殊的 FormFilter
Bean 以为下游应用程序重建表单正文。在运行过滤器链之前读取请求参数的任何 Servlet 过滤器都需要在 FormFilter
之前 排序。请参见以下示例。
Because of the way Servlet Containers handle request parameters, when a Spring WebMVC application receives a content type of application/x-www-form-urlencoded
, Servlet containers combine those with query parameters into "request" parameters. A special FormFilter
bean is included in Spring Cloud Gateway Server MVC to rebuild the form body for downstream applications. Any Servlet Filter that reads request parameters before the filter chain is run will need to be ordered before FormFilter
. See the example below.
import jakarta.servlet.Filter;
import org.springframework.cloud.gateway.server.mvc.filter.FormFilter;
import org.springframework.core.Ordered;
class MyFilter implements Filter, Ordered {
@Override
public int getOrder() {
return FormFilter.FORM_FILTER_ORDER - 1;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
// ...
filterChain.doFilter(request, response);
// ...
}
}