参考:
Spring MVC 基于URL的映射规则(注解版)
SpringMVC:学习笔记(2)——RequestMapping及请求映射
URL路径映射
现在我们已经可以利用@RequestMapping处理URL请求了,但是一个控制器可能要处理多个URL路径的请求,这时候就需要用到URL路径映射了。
基于注解风格的Spring MVC就是通过这个方法来定义映射的url的,常使用的方式如下:
1.普通的url路径映射
这种是最简单的url映射,可以接收到localhost:8080/contextName/hello这样的请求
@RequestMapping("/hello")
public @ResponseBody String test() {
return "hello!";
}
RequestMapping可以同时指定多个url,映射到同一个应答逻辑中:
//普通的url路径映射
@RequestMapping(value={"/multi1","/multi2","/test/multi"})
public @ResponseBody String multiUrl() {
return "test multi url";
}
2.ANT风格路径
Ant 风格资源地址支持 3 种匹配符:
– ?:匹配文件名中的一个字符
– *:匹配文件名中的任意字符
– **:** 匹配多层路径
@RequestMapping 还支持 Ant 风格的 URL:
– /user/*/createUser:
匹配/user/aaa/createUser、/user/bbb/createUser 等 URL
– /user/**/createUser:
匹配/user/createUser、/user/aaa/bbb/createUser 等 URL
– /user/createUser??:
匹配/user/createUseraa、/user/createUserbb 等 URL
基于通配风格的url映射,实例如下:
第一种:
@RequestMapping(value="/ant1?")
public @ResponseBody String ant1(){
return "ant1?";
}
支持下面风格:
localhost:8080/context/ant12 或者
localhost:8080/context/ant1a
第二种:
@RequestMapping(value="/ant2*")
public @ResponseBody String ant2(){
return "ant2*";
}
支持下面风格:
localhost:8080/context/ant2aaaa 或者
localhost:8080/context/ant2
第三种:
@RequestMapping(value="/ant3/*")
public @ResponseBody String ant3(){
return "ant3/*";
}
支持下面风格:
localhost:8080/context/ant3/aaaa 或者
localhost:8080/context/ant3/123
第四种:
@RequestMapping(value="/ant4/**")
public @ResponseBody String ant4(){
return "ant4/**";
}
支持下面风格
localhost:8080/context/ant4/ 或者
localhost:8080/context/ant4/aaa 或者
localhost:8080/context/ant4/aaa/123
3.URL模板模式映射
说明:
1.带占位符的 URL 是 Spring3.0 新增的功能,该功能在SpringMVC 向 REST 目标挺进发展过程中具有里程碑的意义。
2.通过 @PathVariable
可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的{xxx}
占位符可以通过@PathVariable("xxx")
绑定到操作方法的入参中。
//基本的URL模板映射
@RequestMapping(value="/user1/{name}")
public @ResponseBody String basicUrl1(@PathVariable("name") String name){
return "hello"+name;
}
@RequestMapping(value="/user2/{name}/test")
public @ResponseBody String basicUrl2(@PathVariable String name){
return "hello"+name+"test";
}
@RequestMapping(value="/user1/{name}/test/{age}")
public @ResponseBody String basicUrl3(@PathVariable String name,@PathVariable int age){
return "hello"+name+" age"+age;
}
4.混用通配(ant)和模板模式映射
//混用
@RequestMapping(value="/ant5/**/{name}")
public @ResponseBody String ant5(@PathVariable String name){
return "ant+url "+name;
}
它能匹配
localhost:8080/context/ant5/123 或者
localhost:8080/context/ant5/aaa/123 或者
localhost:8080/context/ant5/aaa/123/test
最后一个会被当做name值
5.基于正则的URL模板模式映射
这个比较有意思,它支持{名称:正则表达式}的写法,以另一种风格限制url的映射。
//正则表达式
@RequestMapping(value="/student/{name:\w+}-{age:\d+}")
public @ResponseBody String regUrl(@PathVariable String name,@PathVariable int age){
return "name:"+name+" age:"+age;
}
例如上面的URL就只能匹配如:
localhost:8080/context/student/wangwu-33 或者
localhost:8080/context/student/zhao4-22
最后
以上就是曾经楼房最近收集整理的关于SpringMVC——RequestMapping及请求映射的全部内容,更多相关SpringMVC——RequestMapping及请求映射内容请搜索靠谱客的其他文章。
发表评论 取消回复