java Spring @RequestMapping 处理特殊字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31057496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:01:05  来源:igfitidea点击:

Spring @RequestMapping handling of special characters

javaspringresturlurlencode

提问by Ammar

I have a REST API like this:

我有一个这样的 REST API:

  @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
  }

My problem is that the id that might be given is in the form:

我的问题是可能给出的 id 格式为:

US%2FCA%2FSF%2FPlastic

Which is a URL encoding of "US/CA/SF/Plastic".

这是“US/CA/SF/Plastic”的 URL 编码。

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?

我的问题是,当一个 % 字符被放入 URL 时,@RequestMapping 不会将它映射到这个方法,它会返回一个 404。有没有办法接受其中包含 % 字符的 ID 作为 URL 的一部分?

回答by Victor Dovgaliuc

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.

您收到此错误是因为将其用作路径变量,它被解码,然后服务器尝试将其与不存在的路径匹配。几年前发布的类似问题:如何匹配具有包含“/”的@pathVariable 的 Spring @RequestMapping?, urlencoded 正斜杠正在破坏 URL

A good option for you would be to change _idfrom @PathVariableto @RequestParamand problem solved, and remove it from path.

你一个很好的选择是改变_id来自@PathVariable@RequestParam和问题解决,从路径中删除它。

回答by Tony Puthenveettil

Hope you can add regex in the path variable like:

希望您可以在路径变量中添加正则表达式,例如:

@RequestMapping(value = "/services/produce/{_id:.+}", 
  method = RequestMethod.PATCH, 
  consumes = MediaType.APPLICATION_JSON_VALUE, 
  produces = MediaType.APPLICATION_JSON_VALUE)