# 1.2 Filters

spring-web模块提供了一些有用的过滤器：

* Form Data
* Forwarded Headers
* Shallow ETag
* CORS

## 1.2.1 Form Data

浏览器只能通过HTTP GET或HTTP POST提交表单数据，但非浏览器客户端也可以使用HTTP PUT，PATCH和DELETE。 Servlet API需要ServletRequest.getParameter\*（）方法来仅支持HTTP POST的表单字段访问。

spring-web模块提供FormContentFilter来拦截内容类型为application /x-www-form-urlencoded的HTTP PUT，PATCH和DELETE请求，从请求主体中读取表单数据，并包装ServletRequest以使 表单数据可通过ServletRequest.getParameter\*（）方法族获得。

## 1.2.2 Forwarded Headers

当请求通过代理（例如负载平衡器）进行处理时，主机，端口和方案可能会更改，这使得从客户端角度创建指向正确的主机，端口和方案的链接带来了挑战。

RFC 7239定义了代理可以用来提供有关原始请求的信息的HTTP转发头。还有其他非标准标头，包括X-Forwarded-Host，X-Forwarded-Port，X-Forwarded-Proto，X-Forwarded-Ssl和X-Forwarded-Prefix。

ForwardedHeaderFilter是一个Servlet过滤器，它根据转发的标头修改请求的主机，端口和方案，然后删除这些标头。

对于转发的标头，存在安全方面的考虑，因为应用程序无法知道标头是由代理添加的，还是由恶意客户端添加的。这就是为什么应配置信任边界处的代理以删除来自外部的不受信任的转发标头的原因。您还可以使用removeOnly = true配置ForwardedHeaderFilter，在这种情况下，它将删除但不使用标头。

## 1.2.3 Shallow ETag

ShallowEtagHeaderFilter筛选器通过缓存写入响应的内容并从中计算MD5哈希值来创建“浅” ETag。 客户端下一次发送时，它会执行相同的操作，但是还会将计算出的值与If-None-Match请求标头进行比较，如果两者相等，则返回304（NOT\_MODIFIED）。

此策略可节省网络带宽，但不会节省CPU，因为必须为每个请求计算完整响应。 如前所述，控制器级别的其他策略可以避免计算。 请参阅HTTP缓存。

该过滤器具有writeWeakETag参数，该参数将过滤器配置为写入弱ETag，类似于以下内容：W /“ 02a2d595e6ed9a0b24f027f2b63b134d6”（在RFC 7232第2.3节中定义）。

## 1.2.4 CORS

Spring MVC通过控制器上的注解为CORS配置提供了细粒度的支持。 但是，当与Spring Security一起使用时，我们建议您依赖内置的CorsFilter，该内置CorsFilter必须在Spring Security的过滤器链之前订购。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.flydean.com/spring-framework-documentation5/webservlet/1.spring-web-mvc/1.2filters.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
