@reqeustBody
- 常用來處理content-type==不是默認的application/x-www-form-urlcoded編碼的內容,比如說:application/json或者是application/xml通過@requestBody可以將請求體中的JSON字符串綁定到相應的bean上,當然,也可 以將其分別綁定到對應的字符串上。
- 在Get請求中,沒有HttpEntity,所以@RequestBody並不適用
- 在Post請求中,因爲必須在請求頭中申明Content-Type,則可以使用
public void login(@requestBody String userName,@requestBody String pwd){
System.out.println(userName+" :"+pwd);
}
假如我有一個User類,擁有如下字段:
public class User {
String userName;
String pwd;
}
那麼上述參數可以改爲以下形式
public void login(@requestBody User user){
}
這種形式會將JSON字符串中的值賦予user中對應的屬性上
注意:JSON字符串中的key必須對應user中的屬性名,否則是請求不過去的
@RequestParam
- 請求處理的方法的參數的類型爲Java基本類型和String.也可以接受對象類型
- 常用來處理content-type爲默認的application/x-www-form-urlcoded編碼
屬性 | 類型 | 是否必要 | 說明 |
---|---|---|---|
name | String | 否 | 指定請求參數綁定的名稱 |
value | String | 否 | name屬性的別名 |
required | boolean | 否 | 指定參數是否必須綁定 |
default | String | 否 | 沒有參數時使用的默認值 |
@PathVariable
- 只支持一個類型爲String的屬性,表示綁定的請求參數的名稱,省略則默認綁定同名的參數。
- 通過 @PathVariable 可以將 URL 中佔位符參數綁定到控制器處理方法的入參中:URL 中的 {xxx} 佔位符可以通過@PathVariable(“xxx”) 綁定到操作方法的入參中。
String edit(@PathVariable("orwModelid") String orwModelid,Model model){
DataMastDO dataMast = dataMastService.get(orwModelid);
model.addAttribute("dataMast", dataMast);
return "system/dataMast/edit";
}
/**
* localhost:8080/springmvc/hello/pathVariable/bigsea
* localhost:8080/springmvc/hello/pathVariable/sea
* 這些URL 都會 執行此方法 並且將 <b>bigsea</b>、<b>sea</b> 作爲參數 傳遞到name字段
* @param name
* @return
*/
@RequestMapping("/pathVariable/{name}")
public String pathVariable(@PathVariable("name")String name){
System.out.println("hello "+name);
return "helloworld";
}
---------------------
作者:胡小海丶
來源:CSDN
原文:https://blog.csdn.net/a67474506/article/details/46361195
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!
什麼都不寫,直接寫參數
- springmvc會自動根據參數名字來注入,所以要名字一致,不然不會注入
總結
- @RequestBody @RequstParam @PathVariable
- 在判斷適用哪一個時,如下:
$.ajax({
url:prefix + '/getUser',
// 數據發送方式
type: "post",
// 接受數據格式
dataType:"json",
contentType: "application/json;charset=utf-8",
// 要傳遞的數據
data:JSON.stringify({'name':'a'}),
// 回調函數,接受服務器端返回給客戶端的值,即result值
success:function(jsons){
}
})
- Post
- 判斷contentType,是"application/json;charset=utf-8", 使用@ReuqestBody
- 判斷contentType,是“application/xml”,使用@RequestBody
- 判斷contentType,是“application/x-www-form-urlcoded”,使用@RequestParam
- Get
- 使用 @PathVariable