URL变量
在Web应用中URL通常不是一成不变的,例如微博两个不同用户的个人主页对应两个不同的URL:http://weibo.com/user1
,http://weibo.com/user2
。我们不能对于每一个用户都编写一个被@RequestMapping
注解的方法来处理其请求,也就是说,对于相同模式的URL(例如不同用户的主页,它们仅仅是URL中的某一部分不同,为他们各自的用户名,我们说它们具有相同的模式)。
定义URL变量规则
可以在@RequestMapping
注解中用{}来表明它的变量部分,例如:
@RequestMapping("/users/{username}")
这里{username}就是我们定义的变量规则,username是变量的名字,那么这个URL路由可以匹配下列任意URL并进行处理:
- /user/xiao
- /user/shen
在默认情况下,变量中不可以包含URL的分隔符/,比如/user/pd1/pd2/就无法被识别。
获取URL变量
在路由中定义变量规则后,通常我们需要在处理方法(也就是@RequestMapping注解的方法)中获取这个URL的具体值,并根据这个值(例如用户名)做相应的操作,可以SpringMVC提供的@PathVariable
注解.
例1:
@RequestMapping("/users/{username}")
@ResponseBody
public String userProfile(@PathVariable String username){
return String.format("user %s", username);
return "user" + username;
}
在上述例子中,当@Controller
处理HTTP请求时,userProfile的参数username会自动设置为URL中对应变量username(同名赋值)的值.
例如当HTTP请求为/user/student
时,URL变量username的值student会被赋给函数参数username,函数的返回值也是student.
默认情况下,Spring会对@PathVariable
注解的变量进行自动赋值。
例2:
@RequestMapping(value="/users/{userId}/topics/{topicId}")
public String test(
@PathVariable(value="userId") int userId,
@PathVariable(value="topicId") int topicId)
如请求的URL为“控制器URL/users/123/topics/456”,则自动将URL中模板变量{userId}和{topicId}绑定到通过@PathVariable注解的同名参数上,即入参后userId=123、topicId=456。
获取多个URL变量
@RequestMapping("/user/{username}/blog/{blogId}")
@ResponseBody
public String getUerBlog(@PathVariable String username , @PathVariable int blogId) {
return "user: " + username + "blog->" + blogId;
}
在默认情况下,@PathVariable
注解的参数可以是一些基本的简单类型:int,long,Date,String等,Spring能根据URL变量的具体值以及函数参数的类型来进行转换,例如/user/pd1/blog/1
,会将"pd1"的值赋给username,而1赋值给int变量blogId。
总结
- 在
@RequestMapping
注解中定义URL变量规则在@RequestMapping
注解方法中获取URL变量@PathVariable
@PathVariable
指定URL变量名,定义多个URL变量