7

Client sends on the server (implementation doesn't matter):

/path/items/ + urlencode(id, SOME_ENCODING)

Consider result URL will be:

/path/items/my%2Fkey

Hence I have on server:

@RequestMapping(value = "/path/items/{identifier}", method = RequestMethod.GET)
public Item get(@PathVariable String identifier) {
try {
    return DAO.getItemByIdentifier(URLDecoder.decode(identifier, SOME_ENCODING))
}
catch (UnsupportedEncodingException e) {
...
}

Is there any way to do it in Spring internally? I mean get identifier already decoded, so I could just:

@RequestMapping(value = "/path/items/{identifier}", method = RequestMethod.GET)
    public Item get(@PathVariable String identifier) {
return DAO.getitemByidentifier(identifier); // already decoded!
    }
fasth
  • 2,232
  • 6
  • 26
  • 37
  • 1
    It is done automatically. When I send a request to `/my%20key`, I get `my key` in the path variable. – JB Nizet Sep 20 '14 at 08:14

2 Answers2

3

You can use Spring's CharacterEncodingFilter class in your web.xml as a filter as follows:

<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>
chenrui
  • 8,910
  • 3
  • 33
  • 43
ravi ranjan
  • 5,920
  • 2
  • 19
  • 18
0

You should set your URIEncoding in tomcat connector in server.xml.

Take a look at: http://tomcat.apache.org/tomcat-5.5-doc/config/http.html

//edit:

you can also try to set up encoding filter in web.xml (or java class) like in: Spring/Rest @PathVariable character encoding

Community
  • 1
  • 1
hi_my_name_is
  • 4,894
  • 3
  • 34
  • 50
  • 1
    Also, I need my junit tests to be passed. And they aren't including Tomcat - only MockMvc. – fasth Sep 22 '14 at 06:54