Spring @RequestMapping 处理特殊字符
我有一个这样的 REST API:
I have a REST API like this:
@RequestMapping(value = "/services/produce/{_id}", method = RequestMethod.PATCH,
consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public String patchObject(@RequestBody PatchObjectRequest obj,
@PathVariable("_id") String id) {
// some code
}
我的问题是可能给出的 id 格式如下:
My problem is that the id that might be given is in the form:
US%2FCA%2FSF%2FPlastic
这是US/CA/SF/Plastic"的URL编码.
Which is a URL encoding of "US/CA/SF/Plastic".
我的问题是,当将 % 字符放入 URL 时,@RequestMapping 不会将其映射到此方法,它将返回 404.有没有办法接受其中包含 % 字符的 ID 作为网址?
My problem is that when a % character is put into the URL the @RequestMapping does not map it to this method and it will return a 404. Is there a way to accept ids that have % character in them as part of the URL?
您收到此错误是因为将它用作路径变量,它被解码,然后服务器尝试将其与不存在的路径匹配.几年前发布的类似问题:如何匹配一个 Spring @RequestMapping 有一个包含/"的@pathVariable?,urlencoded 正斜杠正在破坏 URL.
You are receiving this error because using it as path variable it is decoded and then server tries to match it to a path that doesn't exits. Similar questions where posted a few years ago: How to match a Spring @RequestMapping having a @pathVariable containing "/"?, urlencoded Forward slash is breaking URL.
一个不错的选择是将 _id
从 @PathVariable
更改为 @RequestParam
并解决问题,并将其从路径中删除.
A good option for you would be to change _id
from @PathVariable
to @RequestParam
and problem solved, and remove it from path.