Spring/Rest @PathVariable character encoding

前端 未结 4 937
生来不讨喜
生来不讨喜 2020-12-01 08:11

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

相关标签:
4条回答
  • 2020-12-01 08:18

    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.

    0 讨论(0)
  • 2020-12-01 08:18

    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" />
    
    0 讨论(0)
  • 2020-12-01 08:22

    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>
    
    0 讨论(0)
  • 2020-12-01 08:43

    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.

    0 讨论(0)
提交回复
热议问题