1.介紹幾種如何處理url中的參數的注解
@PathVaribale 獲取url中的數據
@RequestParam 獲取請求參數的值
@GetMapping 組合注解,是 @RequestMapping(method = RequestMethod.GET) 的縮寫
(1)PathVaribale 獲取url中的數據
看一個例子,如果我們需要獲取Url=localhost:8080/hello/id中的id值,實現代碼如下:
1 @RestController 2 public class HelloController { 3 @RequestMapping(value="/hello/{id}/{name}",method= RequestMethod.GET) 4 public String sayHello(@PathVariable("id") Integer id,@PathVariable("name") String name){ 5 return "id:"+id+" name:"+name; 6 } 7 }
在瀏覽器中 輸入地址: localhost:8080/hello/100/helloworld 然后會在html頁面上打印出:
id:81
同樣,如果我們需要在url有多個參數需要獲取,則如下代碼所示來做就可以了。
1 @RestController 2 public class HelloController { 3 @RequestMapping(value="/hello/{id}/{name}",method= RequestMethod.GET) 4 public String sayHello(@PathVariable("id") Integer id,@PathVariable("name") String name){ 5 return "id:"+id+" name:"+name; 6 } 7 }
在瀏覽器中輸入地址: localhost:8080/hello/100/helloworld 然后會在html頁面上打印出:
id:100 name:helloworld
以上,通過 @PathVariable 注解來獲取URL中的參數時的前提條件是我們知道url的格式時怎么樣的。
只有知道url的格式,我們才能在指定的方法上通過相同的格式獲取相應位置的參數值。
一般情況下,url的格式為: localhost:8080/hello?id=98 ,這種情況下該如何來獲取其id值呢,這就需要借助於 @RequestParam 來完成了
2.@RequestParam 獲取請求參數的值
例如:
@RestController public class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) public String sayHello(@RequestParam("id") Integer id){ return "id:"+id; } }
在瀏覽器中輸入地址: localhost:8080/hello?id=1000 ,可以看到如下的結果:
id:1000
當我們在瀏覽器中輸入地址: localhost:8080/hello?id ,即不輸入id的具體值,此時返回的結果為null。具體測試結果如下:
id:null
但是,當我們在瀏覽器中輸入地址: localhost:8080/hello ,即不輸入id參數,則會報如下錯誤:
whitelable Error Page錯誤
@RequestParam 注解給我們提供了這種解決方案,即允許用戶不輸入id時,使用默認值,具體代碼如下:
1 @RestController 2 public class HelloController { 3 @RequestMapping(value="/hello",method= RequestMethod.GET) 4 //required=false 表示url中可以不穿入id參數,此時就使用默認參數 5 public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){ 6 return "id:"+id; 7 } 8 }
如果在url中有多個參數,即類似於 localhost:8080/hello?id=98&&name=helloworld 這樣的url,同樣可以這樣來處理。具體代碼如下:
1 @RestController 2 public class HelloController { 3 @RequestMapping(value="/hello",method= RequestMethod.GET) 4 public String sayHello(@RequestParam("id") Integer id,@RequestParam("name") String name){ 5 return "id:"+id+ " name:"+name; 6 } 7 }
在瀏覽器中的測試結果如下: localhost:8080/hello?id=1000&name=helloworld 地址,就會顯示下面的內容:
id:1000 name:helloworld
3.@GetMapping 組合注解
@GetMapping 是一個組合注解,是 @RequestMapping(method = RequestMethod.GET) 的縮寫。該注解將HTTP Get 映射到 特定的處理方法上。
即可以使用 @GetMapping(value = “/hello”) 來代替 @RequestMapping(value=”/hello”,method= RequestMethod.GET) 。即可以讓我們精簡代碼。
1 @RestController 2 public class HelloController { 3 //@RequestMapping(value="/hello",method= RequestMethod.GET) 4 @GetMapping(value = "/hello") 5 //required=false 表示url中可以不穿入id參數,此時就使用默認參數 6 public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){ 7 return "id:"+id; 8 } 9 }
4.PostMapping組合注解:
方法同GetMapping
其它:
SpringMVC接收參數分情況有很多方式,用於綁定參數或者接收參數的注解有很多,當然springboot也一樣,因為SpringBoot用的就是SpringMVC。我們大致可以根據它們處理request的方式不同,分成四類。
@RequestParam ,@RequestBody //處理request body部分的注解 @PathVariable //處理request 動態url的(resultful風格)注解 @RequestHeader @CookieValue //處理request頭部信息的注解 @SessionAttributes @ModelAttributes //處理attributesd的注解
1,通常情況下,我們用名字匹配原則就可以接收參數
直接把表單的參數寫在Controller相應的方法的形參中,適用於get方式提交,不適用於post方式提交。
url為:http:127.0.0.1/login?userName=1111&pwd=2222
@RequestMapping(“/login”) public void login(String loginname,String pwd) { system.out.println(loginname+“:”+pass); }
或者
通過一個bean來接收,post方式和get方式都可以。
public Class User{ private String userName; private String pwd; //setting和getting方法 } @requestMapping(“/login”) public void login(User user){ System.out.println(userName+“ :”+pwd); }
當然可以通過HttpServletRequest接收,post方式和get方式都可以。
@RequestMapping(“/login”) public String addUser2(HttpServletRequest request) { String username=request.getParameter(“username”); String password=request.getParameter(“pwd”); System.out.println(“username is:”+username); System.out.println(“password is:”+password); return “demo/index”; }
2.@RequestParam注解用於將指定的請求參數賦值給方法的參數。
雖然第一種方法可以,但是方法的參數要跟前端一樣,這樣不方便,而且為空時不能設置默認值,於是有了@RequestParam注解
屬性 | 類型 | 是否必要 | 說明 |
---|---|---|---|
name | String | 否 | 指定綁定請求的參數 |
value | String | 否 | name屬性的別名,就是方法的參數名 |
reuuired | boolean | 否 | 指定方法是否綁定,如果綁定,方法參數必要有值 |
defaultValue | String | 否 | 如果請求沒有傳遞值,而給方法參數默認的值 |
@RequestMapping(“/login”) public void login(@RequestParam(name=“loginname”) String loginname,@RequestParam(name=“passname”,value=“pass”) String pass) { system.out.println(loginname+“:”+pass); }
3.@RequestBody將請求體中的JSON字符串綁定到相應的bean上,當然,也可以將其分別綁定到對應的字符串上。
上面都是普通的字段,但是json字符串怎么接收呢,於是有了@RequestBody。將前台使用get和post方式提交數據時,數據編碼格式由請求頭ContentType指定,可以分這幾種情況:
application/x-www-form-urlencoded:可以用@RequestParam很方便的接收,當然@RequestBody也可以
application/json或者application/xml:只能用@RequestBody接收
multipart/form-data:.@RequestBody不能接收這種
@requestMapping(“/login”) public void login(@requestBody String userName,@requestBody String pwd){ System.out.println(userName+“ :”+pwd); } $.ajax({ url:“/login”, type:“POST”, data:‘{“userName”:”admin”,”pwd”,”admin123”}’, content-type:“application/json charset=utf-8”, //必須application/json success:function(data){ alert(“request success ! “); } });
這種情況是將JSON字符串中的兩個變量的值分別賦予了兩個字符串,但是如果很多呢,這樣我們就可以@RequestBody和JavaBean來接收
public Class User{ private String userName; private String pwd; //setting和getting方法 } @requestMapping(“/login”) public void login(@requestBody User user){ System.out.println(userName+“ :”+pwd); }
$.ajax({ url:“/login”, type:“POST”, data:‘{“userName”:”admin”,”pwd”,”admin123”}’, content-type:“application/json charset=utf-8”, success:function(data){ alert(“request success ! “); } });
說明:
@RequestBody主要用來接收前端傳遞給后端的json字符串中的數據的(請求體中的數據的);
GET方式無請求體,所以使用@RequestBody接收數據時,前端不能使用GET方式提交數據,而是用POST方式進行提交。
在后端的同一個接收方法里,@RequestBody 與@RequestParam()可以同時使用,@RequestBody最多只能有一個,而@RequestParam()可以有多個。
注:一個請求,只有一個RequestBody;一個請求,可以有多個RequestParam
4.@PathVariable注解可以方便的得到url中的動態參數,@PathVariable注解只有一個屬性name,用來綁定參數的名稱,如果不填,則默認是方法的參數名。
@requestMapping(“/login/{userId}”) public void login(@PathVariable String userId){ System.out.println(userId); } @requestMapping(“/login/{userId}”) public void login(@PathVariable(name=“userId”) String username){ System.out.println(username); }
說明:
可以在@RequestMapping注解中用{}來表明它的變量部分,這種被稱為resultful風格,例如:
@RequestMapping(“/login/{userId}”)
這里{userId}就是我們定義的變量規則,userId是變量的名字,那么這個URL路由可以匹配下列任意URL並進行處理:
/login/tianmaying /login/ricky /login/tmy1234
注意:在默認情況下,變量中不可以包含URL的分隔符/,例如路由不能匹配/users/tianmaying/ricky,即使你認為tianmaying/ricky是一個存在的用戶名
5.@CookieValue 用於將請求的cookie數據映射到方法的參數上。
屬性 | 類型 | 是否必要 | 說明 |
---|---|---|---|
name | String | 否 | 指定綁定請求的參數 |
value | String | 否 | name屬性的別名,就是方法的參數名 |
reuuired | boolean | 否 | 指定方法是否綁定,如果綁定,方法參數必要有值 |
defaultValue | String | 否 | 如果請求沒有傳遞值,而給方法參數默認的值 |
@RequestMapping(“/login”) public void login(@CookieValue(value=“NAME”,defaultValue “”) String sessionId) { system.out.println(sessionId); }
上面會把NAME的值給sessionId,如果沒有這個cookie,則默認為空。
對ajax請求中的json字符串的一些補充:
@RequestBody 接收客戶端發送的ajax請求中的json字符串,后端自動轉換為User對象
前端
var username = $('#username').val(); var password = $('#password').val(); var data = {username : username , password: password}; if(username != "" && password != ""){ $.ajax({ type: "post", url: "${pageContext.request.contextPath}/user/login", dataType: "json", contentType: "application/json",//設置類型為json data: JSON.stringify(data),//數據要經過這個進行處理轉為json字符串 //JSON.stringify() 方法用於將 JavaScript 值轉換為 JSON 字符串 success: function (msg) { //處理 }, error:function () { alert("錯誤") } }); }else { alert('請輸入賬號密碼') }
controller
@PostMapping(value = "/login") @ResponseBody public String login(@RequestBody User pass_user,HttpSession session){ User user = userService.login(pass_user.getUsername(), pass_user.getPassword()); if (user != null) { session.setAttribute("user",user); return "1"; } return "0"; }
也可以用map接收
@PostMapping(value = "/login") @ResponseBody public String login(@RequestBody Map<String,Object> pass_user,HttpSession session){ User user = userService.login(pass_user.get("username").toString(), pass_user.get("password").toString()); if (user != null) { session.setAttribute("user",user); return "1"; } return "0"; }
總結:
1.json字符串和JavaBean對象互相轉換的過程中,需要使用jackson的jar包
2.前端Ajax默認使用json對象的形式上傳數據 可以修改contenType =“application/json” 上傳json字符串類型
maven加入的依賴
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.0</version> </dependency>
1、以RequestParam接收
前端傳來的是json數據不多時:[id:id],可以直接用@RequestParam來獲取值
@Autowired private AccomodationService accomodationService; @RequestMapping(value = "/update") @ResponseBody public String updateAttr(@RequestParam ("id") int id) { int res=accomodationService.deleteData(id); return "success"; }
2、以實體類方式接收
前端傳來的是一個json對象時:{【id,name】},可以用實體類直接進行自動綁定
@Autowired private AccomodationService accomodationService; @RequestMapping(value = "/add") @ResponseBody public String addObj(@RequestBody Accomodation accomodation) { this.accomodationService.insert(accomodation); return "success"; }
3、以Map接收
前端傳來的是一個json對象時:{【id,name】},可以用Map來獲取
@Autowired private AccomodationService accomodationService; @RequestMapping(value = "/update") @ResponseBody public String updateAttr(@RequestBody Map<String, String> map) { if(map.containsKey("id"){ Integer id = Integer.parseInt(map.get("id")); } if(map.containsKey("name"){ String objname = map.get("name").toString(); } // 操作 ... return "success"; }
4、以List接收
當前端傳來這樣一個json數組:[{id,name},{id,name},{id,name},...]時,用List<E>接收
@Autowired private AccomodationService accomodationService; @RequestMapping(value = "/update") @ResponseBody public String updateAttr(@RequestBody List<Accomodation> list) { for(Accomodation accomodation:list){ System.out.println(accomodation.toString()); } return "success"; }
SpringMVC接收List型參數
1、controller
@RequestMapping("/postList") @ResponseBody public String postList(@RequestBody List<TestL> testL){ System.out.println(testL); return null; }
需要注意點:參數前面必須有注解 @RequestBody
2、ajax請求
var testList=[]; var user={}; user.id=1; user.name='jack'; testList.push(user); var user2={}; user2.id=2; user2.name='tom'; testList.push(user2); $.ajax({ // headers必須添加,否則會報415錯誤 headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, type: 'POST', dataType: "json", //表示返回值類型,不必須 data: JSON.stringify(testList), url: '/test/postList', success: function(){ alert('success'); } });
需要注意點:1、參數是數組類型
2、傳入data時,轉換 JSON.stringify(testList)
3、必須有headers: {
'Accept': 'application/json', 'Content-Type': 'application/json' }
最后再看下TestL類,沒有特別之處(不用包裝)。
public class TestL { private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }