Spring @PathVariable – Why is value truncated after the last (.)dot?
Review the below @PathVariable
example.
@RequestMapping("/site")
public class SiteController {
@RequestMapping(value = "/{q}", method = RequestMethod.GET)
public ModelAndView display(@PathVariable("q") String q) {
return getModelAndView(q, "site");
}
}
See the following cases :
- For input
/site/google
,q = google
- For input
/site/google.com
,q = google
where is the.com
? - For input
/site/google.com.my
,q = google.com
- For input
/site/google.com.my.abc
,q = google.com.my
- For input
/site/cloud.google.com
,q = cloud.google
Why is the value truncated after the last (.)dot?
P.S Tested with Spring 3,4 and 5.
Solution
By default, Spring Web MVC considers the value after the last dot or period (.) as a file extension and truncates them automatically.
To fix it, we can use regex mapping {varName:regex}
, this regex pattern .+
will matches everything.
@RequestMapping("/site")
public class SiteController {
@RequestMapping(value = "/{q:.+}", method = RequestMethod.GET)
public ModelAndView display(@PathVariable("q") String q) {
return getModelAndView(q, "site");
}
}
Now, for input /site/google.com
, the q
will display the correct google.com
.
Another solution is to configure Spring MVC that extends WebMvcConfigurerAdapter as such:
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseSuffixPatternMatch(false);
}