@RequestParam,@PathVariable,@ResponseBody,@RequestBody,@ModelAttribute學習

一、@RequestParam使用於參數上,用於將請求參數映射到指定參數變量上html

例如:ajax

1 @RequestMapping(value="/hello",method=RequestMethod.GET) 2 
3 public String testPara(@RequestParam String str){ 4 
5 System.out.println(str); 6 
7 return "hello"; 8 
9 }

當咱們訪問 http://localhost:8080/springMVC/hello?str=xx 的時候,會將xx注入到testParam方法中的str中,你會看到輸出xxspring

固然此時你在瀏覽器的參數名稱必須跟testPara中的參數同樣即必須都爲str,假如你想使用不一樣的參數名稱,就必須在@RequestParam(" anothername") str 指定json

參數名,這樣當你訪問 http://localhost:8080/springMVC/hello?anothername=xx ,就會將xx注入到str中了。springMVC中默認就是開啓 @RequestParam功能的,瀏覽器

你直接訪問http://localhost:8080/springMVC/hello?str=xx在程序中不寫@RequestParam,仍是會注入到str參數中。固然咱們最好仍是寫一下,有助於理解和利於服務器

代碼的閱讀 app

二、@PathVariable與@RequestParam相似,可是它是用於rest風格 訪問時候獲取參數的方式,使用這個註解前提是在@RequestMapping中必須指定模板,否則異步

訪問可能出現400,服務器不懂你要幹嗎。例以下面的例子:jsp

 1 public String testPath(@PathVariable String para)  2 
 3 @RequestMapping(value="/hello/{para}",method=RequestMethod.GET) //在reqestMapping指定了模板{para}
 4 
 5 public String testPath(@PathVariable String para){  //參數名字必定要跟模板的名字同樣,若是不想跟模板同樣,能夠寫成這樣@PathVariable("para")String other
 6 
 7 System.out.println(para);  8 
 9 return "hello"; 10 
11 }

訪問:http://localhost:8080/springMv/spring/hello/anty    控制檯輸出參數anty async

三、 @responsebody表示該方法的返回結果直接寫入HTTP response body中
通常在異步獲取數據時使用,在使用@RequestMapping後,返回值一般解析爲跳轉路徑,加上@responsebody後返回結果不會被解析爲跳轉路徑,而是直接寫入HTTP response body中響應給客戶端。好比異步獲取json數據,加上@responsebody後,會直接返回json數據。使用時機:返回的數據不是html標籤的頁面,而是其餘某種格式的數據時(如json、xml等)使用;

例如如下代碼:

服務器端:

 1 @RequestMapping(value="/ajaxRequest")  2 
 3 @ResponseBody  4 
 5 public String ajax(String str){  6 
 7 str="sb";  8 
 9 return str; 10 
11 }

 客戶端代碼:

         $.ajax({

           type:"POST",

            async : false,

            url:"spring/ajaxRequest",

            success:function(data){

            alert(data);               

            } 

});

點擊頁面按鈕訪問服務器,彈出sb 

四、@RequestBody

做用: 

      i) 該註解用於讀取Request請求的body部分數據,使用系統默認配置的HttpMessageConverter進行解析,而後把相應的數據綁定到要返回的對象上;

      ii) 再把HttpMessageConverter返回的對象數據綁定到 controller中方法的參數上。

使用時機:

A) GET、POST方式提時, 根據request header Content-Type的值來判斷:

·     application/x-www-form-urlencoded, 可選(即非必須,由於這種狀況的數據@RequestParam, @ModelAttribute也能夠處理,固然@RequestBody也能處理);

·     multipart/form-data, 不能處理(即便用@RequestBody不能處理這種格式的數據);

·     其餘格式, 必須(其餘格式包括application/json, application/xml等。這些格式的數據,必須使用@RequestBody來處理);

B) PUT方式提交時, 根據request header Content-Type的值來判斷:

·     application/x-www-form-urlencoded, 必須;

·     multipart/form-data, 不能處理;

·     其餘格式, 必須;

說明:request的body部分的數據編碼格式由header部分的Content-Type指定;m 

requestbody能夠直接將客戶端發來的ajax請求的json對象注入到服務端的對象中,可是json對象的字段必須跟後臺對象的字段對應,

例如 var user{"username":"tom"} 後臺的User對象必需要有username 這個字段。既然是使用異步,那麼requestBody不少時候是跟responseBody搭配着一塊兒使用!!例以下列代碼:

//@RequestMapping(value="/ajaxRequest")

//@ResponseBody

//public String ajax(@RequestBody User user){

//System.out.println(user.getUsername());

//return user.getUsername();

//}

客戶端代碼:

  var m = { 

                "username":'fuckyou'

            };

        $.ajax({

            type:"POST",

            async : false,

            url:"spring/ajaxRequest",

            dataType:"json",

            contentType:"application/json; charset=utf-8",//必定要加這一句發送內容爲json

            data:JSON.stringify(m),//requestbody接收的是json字符串,因此得將json對象進行轉換不然報415錯誤類型沒法識別

            success:function(data){

                alert("return map success!");               

            }

});

在客戶端發起請求,服務器控制檯輸出fuckyou,表示username字段注入到user對象 

五、@ModelAttribute    一種是放在方法上面,一種是放在參數上面(比較經常使用的是放在參數前面)

放在方法上面:

 1  @ModelAttribute  2     public User User(User userd){  3         userd.setUsername("fuckg");  4         return userd;  5         
 6  }  7     @RequestMapping(value="/hello",method=RequestMethod.GET)  8     public String testPara(User u){  9  System.out.println(u.getUsername()); 10         return "hello"; 11     }

在到達全部requestMapping以前 會被modelAttribute攔截,在客戶端提交表單 會將對應 的屬性 注入到Userd 對象中,而後springMVC默認會將usrerd對象 放入視圖中,以便訪問, 咱們能夠在hello頁面 使用{user.username} 訪問,

這裏要注意的是 無論參數是寫成userd仍是寫成users,都只能經過user.username訪問到,spring是按照該對象類型 的小寫來訪問,User類對象,因此在頁面就經過user訪問屬性。 

第二種是將註解放到參數前:

1 @RequestMapping("/modd") //默認使用modelAttribute,若是去掉效果仍是同樣
2     public String testModelAttr(@ModelAttribute User userqqq){ 3  System.out.println(userqqq.getUsername()); 4         return "md"; 5         
6     }
 

這裏也是表單提交過來的參數 會注入到user 對象的對應屬性上(這裏表單提交過來的數據,不能使用@RequestBody替換ModelAttribute,requestBody經常使用在異步提交json數據,在這換成requestBody的話會報415錯誤),而後spring 也會把該對象放入視圖中,在md.jsp頁面,就能夠經過${user.username}訪問,固然這裏也是同樣 

無論參數寫成什麼樣,仍是按照該類型的小寫字母來訪問,因此不是按userqqq來訪問,直接按照User-->小寫user訪問。

嘗試了一下去除ModelAttribute的效果,發現仍是可用,說明,是spring 默認開啓了參數前 的ModelAttribute註解,不過要用的時候仍是寫出來 利於代碼閱讀 

@requestBody 和@ModelAttribute 均可以用來綁定請求數據到參數上,在個人理解範圍內:requestBody主要是將異步請求ajax,json字符串綁定到對象上,requestBody

只接受json字符串,因此記得使用JSON.stringif方法將json對象轉成字符串,  而ModelAttribute主要接收來自表單或者url?para參數,將參數綁定到對象上。

轉自:https://blog.csdn.net/zz210891470/article/details/59719251

相關文章
相關標籤/搜索