[英]Handling special characters in REST API
I am having following URL 我有以下网址
http://context_path/info/abc/def
which gets converted like 转换成像
http://context_path/info/abc%2Fdef
Where as my controller mapping is: 我的控制器映射在哪里:
@RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
here 'id' contains forward slash (/). 这里'id'包含正斜杠(/)。 So when I hit the URL I get 400 Bad Request . 所以,当我点击URL时,我得到400 Bad Request 。
I know the possible solutions 我知道可能的解决方案
@RequestParam
instead of @PathVariable
. 使用@RequestParam
而不是@PathVariable
。 But above solution are not possible for me. 但上面的解决方案对我来说是不可能的。
Q. Is there any other solution like (using regular expression or changing the mapping or anything else) to the problem ? 问:是否有任何其他解决方案(使用正则表达式或更改映射或其他任何内容)来解决问题? Also how the tomcat treats other special characters ('.' , ''' , ':' , ',') correctly and controller gets hit but not for '/' . 另外tomcat如何正确处理其他特殊字符('。',''',':',',') ,控制器被命中,但不是'/' 。
Tried but not working : 尝试但没有工作:
1) @RequestMapping(value = "/info/{id:.*}", method = RequestMethod.GET)
2) @RequestMapping(value = "/info/{id}/**", method = RequestMethod.GET)
3) @RequestMapping(value = "/info/**", method = RequestMethod.GET)
It is not nice, but you can use Base64 transformation . 它不是很好,但您可以使用Base64转换 。
So you client will send an encoded id
and you decode it back in your controller. 因此,您的客户端将发送编码的id
,然后在控制器中对其进行解码。
import org.apache.commons.codec.binary.Base64;
@RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
public String get(@PathVariable String id) {
final String realId = new String(new Base64(true).encodeBase64URLSafe(id));
[...]
}
EDIT: You should use url save implementation of Base64: 编辑:您应该使用Base64的url save实现 :
You can use something like this How to handle requests that includes forward slashes (/)? 你可以使用这样的东西如何处理包含正斜杠(/)的请求?
But it has it's limitations, I would suggest you to replace the forward slash with something else like '#' while calling the api and then again replace it back to forward slash before processing it in rest controller. 但它有它的局限性,我建议你在调用api的同时用'#'替换正斜杠,然后再将它替换回正斜杠,然后再在rest控制器中处理它。
If replacing while calling the api is not possible then you can use filter and replace the data there. 如果在调用api时无法替换,则可以使用过滤器并替换那里的数据。
You can use regular expressions to define your url. 您可以使用正则表达式来定义您的网址。 Refer http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-uri-templates-regex 请参阅http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-uri-templates-regex
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.