@PathVariable綁定URI模板變量值
@PathVariable用于將請求URL中的模板變量映射到功能處理方法的參數上。
1
2
3
4
|
@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。
代碼在PathVariableTypeController中。
@RequestParam(參數綁定到控制器)和@PathVariable(參數綁定到url模板變量)
spring mvc:練習 @RequestParam和@PathVariable
-
@RequestParam
: 注解將請求參數綁定到你的控制器方法參數 -
@PathVariable
: 注釋將一個方法參數綁定到一個URI模板變量的值
@RequestParam: 注解將請求參數綁定到你的控制器方法參數
1
2
3
|
@RequestMapping (value= "/example/user" ) public String UserInfo(Model model, @RequestParam (value= "name" , defaultValue= "Guest" ) String name) |
實例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package springmvc; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class RequestParamExampleController { @RequestMapping (value= "/example/user" ) public String UserInfo(Model model, @RequestParam (value= "name" , defaultValue= "Guest" ) String name) { model.addAttribute( "name" , name); if ( "admin" .equals(name)) { model.addAttribute( "email" , "admin@google.com" ); } else { model.addAttribute( "email" , "not set" ); } return "example_user" ; } } |
@PathVariable: 注釋將一個方法參數綁定到一個URI模板變量的值
1
2
3
4
5
|
@RequestMapping (value= "/example/info/{language}/{id}/{name}" ) public String userInfo2(Model model, @PathVariable (value= "language" ) String language, @PathVariable (value= "id" ) Long id, @PathVariable (value= "name" ) String name) |
實例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
package springmvc; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.PathVariable; @Controller public class RequestParamExampleController { @RequestMapping (value= "/example/person/{name}/{age}" ) public String userPerson(Model model, @PathVariable (value= "name" ) String name, @PathVariable (value= "age" ) Long age) { model.addAttribute( "name" , name); model.addAttribute( "age" , age); String desc = "" ; if (age > 20 ) { desc = "oldman" ; } else { desc = "yongman" ; } model.addAttribute( "desc" , desc); return "example_person" ; } } |
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/PKWind/article/details/49757219