在哪里以及如何解码@PathVariable

fas*_*sth 7 java rest url spring

客户端在服务器上发送(实现无关紧要):

/path/items/ + urlencode(id, SOME_ENCODING)
Run Code Online (Sandbox Code Playgroud)

考虑结果URL将是:

/path/items/my%2Fkey
Run Code Online (Sandbox Code Playgroud)

因此我在服务器上:

@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) {
...
}
Run Code Online (Sandbox Code Playgroud)

在内部有没有办法在Spring中做到这一点?我的意思是标识符已经解码,所以我可以:

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

fre*_*man 0

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

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

//编辑:

您还可以尝试在 web.xml (或 java 类)中设置编码过滤器,例如: Spring/Rest @PathVariable 字符编码