Spring @RequestMapping处理特殊字符

时间:2015-06-25 18:00:23

标签: java spring rest url urlencode

我有一个这样的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
  }

我的问题是可能提供的ID格式为:

US%2FCA%2FSF%2FPlastic

这是" US / CA / SF / Plastic"。

的网址编码

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

2 个答案:

答案 0 :(得分:7)

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. A good option for you would be to change _id from @PathVariable to @RequestParam and problem solved, and remove it from path.

答案 1 :(得分:2)

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

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