Spring @RequestMapping handling of special characters

21.2k views Asked by At

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
  }

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

US%2FCA%2FSF%2FPlastic

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

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?

2

There are 2 answers

1
Victor Dovgaliuc On BEST ANSWER

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.

0
Tony Puthenveettil On

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)