Spring, @PathVariable, dots and truncated values...
If you are using a Spring @PathVariable
with a @RequestMapping
to map the end of a request URI that contains a dot, you may end up wondering why you end up with a partial value in your variable - with the value truncated at the last dot. For example, if you had the mapping:
@RequestMapping(value = "/test/{foo}", method=RequestMethod.GET)
public void test(@PathVariable String foo){
}
and you made a request to /test/fred.smith
, then foo="fred"
and the .smith
is nowhere to be seen. Similarly, if you requested /test/fred.smith.jnr
, then foo=fred.smith
and the .jnr
would be absent. (Spring thinks these are file extensions and helpfully removes them for you.)
The simple fix for this is to add a regex to the RequestMapping variable definition as per:
@RequestMapping(value = "/test/{foo:.*}", method=RequestMethod.GET)
public void test(@PathVariable String foo){
}
Then for /test/fred.smith
you will get foo="fred.smith"
.
Others have obviously encountered the same issue - see the StackExchange questions Spring MVC PathVariable getting truncated and Spring MVC Path Variable with dot is getting truncated for some additional information.