【发布时间】:2010-12-17 13:17:50
【问题描述】:
在我使用的环境(Tomcat 6)中,路径段中的百分比序列在映射到@PathVariable 时显然是使用 ISO-8859-1 解码的。
我希望它是 UTF-8。
我已经将 Tomcat 配置为使用 UTF-8(使用 server.xml 中的 URIEncoding 属性)。
Spring/Rest 是否自己进行解码?如果是,我在哪里可以覆盖默认编码?
附加信息;这是我的测试代码:
@RequestMapping( value = "/enc/{foo}", method = RequestMethod.GET )
public HttpEntity<String> enc( @PathVariable( "foo" ) String foo, HttpServletRequest req )
{
String resp;
resp = " path variable foo: " + foo + "\n" +
" req.getPathInfo(): " + req.getPathInfo() + "\n" +
"req.getPathTranslated(): " + req.getPathTranslated() + "\n" +
" req.getRequestURI(): " + req.getRequestURI() + "\n" +
" req.getContextPath(): " + req.getContextPath() + "\n";
HttpHeaders headers = new HttpHeaders();
headers.setContentType( new MediaType( "text", "plain", Charset.forName( "UTF-8" ) ) );
return new HttpEntity<String>( resp, headers );
}
如果我使用以下 URI 路径发出 HTTP GET 请求:
/TEST/enc/%c2%a3%20and%20%e2%82%ac%20rates
这是 UTF-8 编码然后百分比编码的形式
/TEST/enc/£ and € rates
我得到的输出是:
path variable foo: £ and ⬠rates
req.getPathInfo(): /enc/£ and € rates
req.getPathTranslated(): C:\Users\jre\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\TEST\enc\£ and € rates
req.getRequestURI(): /TEST/enc/%C2%A3%20and%20%E2%82%AC%20rates
req.getContextPath(): /TEST
这对我来说表明 Tomcat(在设置 URIEncoding 属性之后)做了正确的事情(请参阅 getPathInfo()),但路径变量仍在 ISO-8859-1 中解码。
答案是:
Spring/Rest 显然使用了请求编码,这是一件很奇怪的事情,因为这是关于 body,而不是 URI。叹息。
添加这个:
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
解决了这个问题。它真的应该更简单。
实际上,情况更糟:
如果该方法确实具有一个请求正文,并且该请求正文未以 UTF-8 编码,则需要额外的 forceEncoding 参数。这似乎可行,但我担心以后会导致更多问题。
另一种方法
同时,我发现可以禁用解码,我指定
<property name="urlDecode" value="false"/>
...在这种情况下,收件人可以做到正确的事情;但这当然会让很多其他事情变得更加困难。
【问题讨论】:
标签: spring rest character-encoding uri