在哪里以及如何解码@PathVariable

时间:2014-09-20 03:43:27

标签: java spring rest url

客户端在服务器上发送(实现并不重要):

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

考虑结果URL将是:

/path/items/my%2Fkey

因此我在服务器上:

@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) {
...
}

有没有办法在Spring内部执行此操作?我的意思是标识符已经解码,所以我可以:

@RequestMapping(value = "/path/items/{identifier}", method = RequestMethod.GET)
    public Item get(@PathVariable String identifier) {
return DAO.getitemByidentifier(identifier); // already decoded!
    }

2 个答案:

答案 0 :(得分:2)

您可以在CharacterEncodingFilter中使用Spring的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>

答案 1 :(得分:0)

您应该在server.xml中的tomcat连接器中设置URIEncoding。

看看:http://tomcat.apache.org/tomcat-5.5-doc/config/http.html

//编辑:

你也可以尝试在web.xml(或java类)中设置编码过滤器,如: Spring/Rest @PathVariable character encoding