Search code examples
javaspringspring-bootspring-datapath-variables

How to pass @PathVariable("timeZoneId") in spring?


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 ?


Solution

  • 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("-","/"));