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
- Spring MVC – URI Template Patterns with Regular Expressions
- Regular Expression Wikipedia
- Spring jira – SPR-6164
Tags : spring mvc spring rest
