Spring REST @RequestMapping extract incorrectly if value contains ‘.’

Problem

See following Spring REST example, if a request such as “http://localhost:8080/site/google.com” is submitted, Spring returns “google“. Look like Spring treats “.” as file extension, and extract half of the parameter value.

SiteController.java
package com.mkyong.web.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
@Controller
@RequestMapping("/site")
public class SiteController {
 
	@RequestMapping(value = "/{domain}", method = RequestMethod.GET)
	public String printWelcome(@PathVariable("domain") String domain,
		ModelMap model) {
 
		model.addAttribute("domain", domain);
		return "domain";
 
	}
 
}

Solution

To fix it, make @RequestMapping supports regular expression, add “.+“, it means match anything. Now, Spring will return “google.com“.

SiteController.java
package com.mkyong.web.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
@Controller
@RequestMapping("/site")
public class SiteController {
 
	@RequestMapping(value = "/{domain:.+}", method = RequestMethod.GET)
	public String printWelcome(@PathVariable("domain") String domain,
		ModelMap model) {
 
		model.addAttribute("domain", domain);
		return "domain";
 
	}
 
}

References

  1. Spring MVC – URI Template Patterns with Regular Expressions
  2. Regular Expression Wikipedia
  3. Spring jira – SPR-6164
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments