先来看一个 SpringMVC 使用 @RequestMapping 和 @PathVariable 的例子
@RequestMapping("/site")
public class SiteController {
@RequestMapping(value = "/{q}", method = RequestMethod.GET)
public ModelAndView display(@PathVariable("q") String q) {
logger.debug("Site : q : {}", q);
return getModelAndView(q, "site");
}
//...
看下面的情况: See the following cases :
- For input /site/google, “q” will display google
- For input /site/google.com, “q” will still display google, the dot (.) is truncated!?
- For input /site/google.com.my, “q” will display google.com, the last dot (.) is truncated!
- For input /site/google.com.my.abc, “q” will display google.com.my
- For input /site/cloud.google.com, “q” will display cloud.google
- The last dot (.) is always getting truncated.
注意: 测试 Spring 的版本是 Spring 3 和 Spring 4.
解决方案: To fix it, add a regex mapping {q:.+} in @RequestMapping 为了解决这个问题, 在 @RequestMapping 里增加正则表达式匹配 : {q:.+}
@RequestMapping("/site")
public class SiteController {
@RequestMapping(value = "/{q:.+}", method = RequestMethod.GET)
public ModelAndView display(@PathVariable("q") String q) {
logger.debug("Site : q : {}", q);
return getModelAndView(q, "site");
}
//... 现在输入 /site/google.com, "q" 将会输出正确的 google.com