客户端在服务器上发送(实现无关紧要):
/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内部做到这一点?我的意思是让 identifier 已经解码,所以我可以:
@RequestMapping(value = "/path/items/{identifier}", method = RequestMethod.GET)
public Item get(@PathVariable String identifier) {
return DAO.getitemByidentifier(identifier); // already decoded!
}
最佳答案
您可以在 web.xml
中使用 Spring 的 CharacterEncodingFilter
类作为过滤器,如下所示:
<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>
关于java - 在哪里以及如何解码@PathVariable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25944964/