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.

Download Source Code

$ git clone https://github.com/mkyong/spring-mvc/

$ cd spring-mvc-basic

$ mvn clean jetty:run

References

One comment on “Spring @PathVariable – Why is value truncated after the last (.)dot?

  1. Another solution is to configure Spring MVC that extends WebMvcConfigurerAdapter as such:

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
    configurer.setUseSuffixPatternMatch(false);
    }

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *