Spring/Rest @PathVariable 字符编码

发布于 2024-10-07 18:44:17 字数 2583 浏览 2 评论 0原文

在我使用的环境(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"/>

......在这种情况下,接收者可以正确的事情;但这当然会让很多其他事情变得更加困难。

In the environment I'm using (Tomcat 6), percent sequences in path segments apparently are decoded using ISO-8859-1 when being mapped to a @PathVariable.

I'd like that to be UTF-8.

I already configured Tomcat to use UTF-8 (using the URIEncoding attribute in server.xml).

Is Spring/Rest doing the decoding on its own? If yes, where can I override the default encoding?

Additional information; here's my test code:

@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 );
}

If I do an HTTP GET request with the following URI path:

/TEST/enc/%c2%a3%20and%20%e2%82%ac%20rates

which is the UTF-8 encoded then percent-encoded form of

/TEST/enc/£ and € rates

the output that I get is:

      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

which to me shows that Tomcat (after setting the URIEncoding attribute) does the right thing (see getPathInfo()), but the path variable is decoded still in ISO-8859-1.

And the answer is:

Spring/Rest apparently uses the request encoding, which is a very strange thing to do, as this is about the body, not the URI. Sigh.

Adding this:

<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>

fixed the problem. It really should be simpler.

And actually, it's worse:

If the method indeed has a request body, and that one isn't encoded in UTF-8, the additional forceEncoding parameter is needed. This seems to work, but I'm concerned it will cause more problems later on.

Another approach

In the meantime, I found out that it's possible to disable the decoding, my specifying

<property name="urlDecode" value="false"/>

...in which case the recipient can to the right thing; but of course this will make lots of other things harder.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

緦唸λ蓇 2024-10-14 18:44:17

我认为您需要向 web.xml 添加过滤器

<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>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

I thing that you need add filter to web.xml

<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>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
天生の放荡 2024-10-14 18:44:17

即使使用字符编码过滤器,路径变量仍然以 ISO-8859-1 进行解码。这是我必须做的来解决这个问题。如果您有任何其他想法,请告诉我!

要查看服务器上实际的 UTF-8 解码字符,您可以执行此操作并查看该值(您需要将“HttpServletRequest httpServletRequest”添加到控制器参数中):

String requestURI = httpServletRequest.getRequestURI();
String decodedURI = URLDecoder.decode(requestURI, "UTF-8");

然后我可以做任何我想做的事情(例如 get手动从解码的 URI 中获取参数),现在我在服务器上有了正确的解码数据。

The path variable is still decoded in ISO-8859-1 for me, even with the Character Encoding Filter. Here is what I had to do to get around this. Please let me know if you have any other ideas!

To see the actual UTF-8 decoded characters on the server, you can just do this and take a look at the value (you need to add "HttpServletRequest httpServletRequest" to your controller parameters):

String requestURI = httpServletRequest.getRequestURI();
String decodedURI = URLDecoder.decode(requestURI, "UTF-8");

I can then do whatever I want (like get the parameter manually from the decoded URI), now that I have the right decoded data on the server.

ぇ气 2024-10-14 18:44:17

尝试在 server.xml 中配置 Tomcat 上的连接器。
useBodyEncodingForURI="true"URIEncoding="UTF-8" 添加到您的连接器标记。
例如:

    <Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           useBodyEncodingForURI="true"
           redirectPort="8443" />

Try to configure connector on Tomcat in server.xml.
Add useBodyEncodingForURI="true" or URIEncoding="UTF-8" to your Connector tag.
For example:

    <Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           useBodyEncodingForURI="true"
           redirectPort="8443" />
伪心 2024-10-14 18:44:17

但是,您必须完全搞乱 Tomcat 配置(URIEncoding)才能使其工作,这不是很糟糕吗?如果 servlet API 提供了一种方法来获取未解码表示形式的路径和请求参数,则应用程序(或 Spring)可以完全自行处理解码。显然,HttpServletRequest#getPathInfo 和 HttpServletRequest#getQueryString 甚至会提供此功能,但对于后者,这意味着 Spring 必须解析和解码查询字符串本身,而不是依赖 HttpServletRequest#getParameter 和朋友。显然他们不这样做,这意味着您不能让 @RequestParam@PathVariable 在不依赖 servlet 容器配置的情况下安全地捕获除 us-ascii 字符串之外的任何内容。

But doesn't it suck that you have to mess with the Tomcat configuration (URIEncoding) at all to make this work? If the servlet API provided a way to obtain the path and request parameters in their undecoded representation, the application (or Spring) could deal with the decoding entirely on its own. And apparently, HttpServletRequest#getPathInfo and HttpServletRequest#getQueryString would even provide this, but for the latter this would mean that Spring would have to parse and decode the query string itself and not rely on HttpServletRequest#getParameter and friends. Apparently they don't do this, which means you can't have @RequestParam or @PathVariable capture anything other than us-ascii strings safely without relying on the servlet container's configuration.

不必了 2024-10-14 18:44:17

今天,当我尝试使用葡萄牙语单词时遇到了这个问题。
SpringBoot 中 Avseiytsev Dmitriy 的答案可以通过以下方式获得:

server.tomcat.uri-encoding=UTF-8

application.properties 文件中

我已经测试过并且可以工作。

例如,如果您在应用程序中使用 TDD 并使用 MockMvc 来测试 GET,请按以下方式操作:

mockMvc.perform(get("/api/v1/categories/" + NAME2)
                    .characterEncoding("UTF-8")
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.name", equalTo(NAME2)));

NAME2 变量是一个字符串:José

Today I had this problem when I tryed to use a word in Portuguese.
The answer of Avseiytsev Dmitriy in SpringBoot can be reached with:

server.tomcat.uri-encoding=UTF-8

in application.properties file

I have tested and this Works.

If you are using TDD in your application and using MockMvc to test a GET for example, do this way:

mockMvc.perform(get("/api/v1/categories/" + NAME2)
                    .characterEncoding("UTF-8")
                    .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.name", equalTo(NAME2)));

The NAME2 variable is a String: José

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文