正则表达式映射

原文:http://www.cnblogs.com/liukemng/p/3726897.html

1.4.URL正则表达式映射:

Spring MVC还支持正则表达式方式的映射配置,我们通过一个测试来展示:

在HelloWorldController添加一个regUrlTest的action,内容如下:

复制代码
@RequestMapping(value="/reg/{name:\\w+}-{age:\\d+}", method = {RequestMethod.GET})
public ModelAndView regUrlTest(@PathVariable(value="name") String name, @PathVariable(value="age") Integer age){
    
    ModelAndView modelAndView = new ModelAndView();   
    modelAndView.addObject("name", name); 
    modelAndView.addObject("age", age); 
    modelAndView.setViewName("regurltest");  
    return modelAndView;
}
复制代码

在views文件夹中新加一个视图regurltest.jsp内容如下:

复制代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    ${name}-${age}
</body>
</html>
复制代码

请求http://localhost:8080/SpringMVCLesson/helloworld/reg/Hanmeimei-18查看结果:

5

请求http://localhost:8080/SpringMVCLesson/helloworld/reg/Hanmeimei-Lilei查看结果(会发现找不到对应的action返回404):

6

 

posted @ 2017-01-04 10:28  云晴  阅读(1014)  评论(0编辑  收藏  举报