0

I have the following @RestController method in Spring Boot 1.5.9:

@GetMapping(value = "/today/{timeZoneId}", produces = MediaType.APPLICATION_JSON_VALUE)
public Instant getToday(@PathVariable("timeZoneId") String timeZoneId) {
  return getNextPublishingDateTime(Instant.now(), timeZoneId);
}

When I GET with /today/Europe/Paris, I have a 404 error.

I tried to GET with /today/Europe%2FParis but also got a 404.

This is due to the slash in the timeZoneId.

How can I use @PathVariable for my timeZoneId in Spring ?

Dimitri Kopriwa
  • 13,139
  • 27
  • 98
  • 204
  • Are you *really* wanting to put that in path ? In REST philosophy, path variables should represent resources. Here, the time-zone would be more suited as a query parameter (as it is only a formatting configuration). – amanin Apr 22 '20 at 08:03
  • Why not use timeZoneId as a request parameter? Duplicate of this issue: https://stackoverflow.com/questions/2334787/how-to-match-a-spring-requestmapping-having-a-pathvariable-containing – sbsatter Apr 22 '20 at 08:05
  • It doesn't have to be a resource, as for instance : `/profile/{username}` is not a resource, and you can check the principal against the username. I agree in general. So far I use `?timeZoneId`, but this question should be taken as a general question about the way of using path variable that include slash. – Dimitri Kopriwa Apr 22 '20 at 08:05
  • Responding to your comment, this might assist you: https://stackoverflow.com/questions/3235219/urlencoded-forward-slash-is-breaking-url Thing is, you cannot pass forward slashes and a few other characters in the url as part of path. – sbsatter Apr 22 '20 at 08:07

2 Answers2

1

One possible way can be as below,

@GetMapping(value = "/today/{timeZoneIdPrefix}/{timeZoneIdSuffix}", produces = MediaType.APPLICATION_JSON_VALUE)
public Instant getToday(@PathVariable("timeZoneIdPrefix") String timeZoneIdPrefix,@PathVariable("timeZoneIdSuffix") String timeZoneIdSuffix) {
  String timeZoneId = timeZoneIdPrefix +"/"+ timeZoneIdSuffix;
  return getNextPublishingDateTime(Instant.now(), timeZoneId);
}

One more way could be, instead of passing like Europe/Paris pass as Europe-Paris and then replace - with /

 return getNextPublishingDateTime(Instant.now(), timeZoneId.replace("-","/"));
Vikas
  • 6,868
  • 4
  • 27
  • 41
0

You get 404 because Spring is expected a only one value after the slash (encoded %2F or not), but in your case you put two values : Europe and Paris.

DPheng
  • 21
  • 6