淺談@RequestMapping @ResponseBody 和 @RequestBody 註解的用法與區別

來源:互聯網
上載者:User

標籤:urlencode   lan   直接   val   注入   key   分數   資訊   asc   

[email protected]

國際慣例先介紹什麼是@RequestMapping,@RequestMapping 是一個用來處理請求地址映射的註解,可用於類或方法上。用於類上,表示類中的所有響應請求的方法都是以該地址作為父路徑;用於方法上,表示在類的父路徑下追加方法上註解中的地址將會訪問到該方法,此處需注意@RequestMapping用在類上可以沒用,但是用在方法上必須有。

例如:

@Controller//設定想要跳轉的父路徑@RequestMapping(value = "/Controllers")public class StatisticUserCtrl {    //如需注入,則寫入需要注入的類    //@Autowired            // 設定方法下的子路經            @RequestMapping(value = "/method")            public String helloworld() {                return "helloWorld";            }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

其原理也非常好瞭解,其對應的 action 就是“ (父路徑) controller/(父路徑下方法路經)method ”。因此,在本機伺服器上存取方法 http://localhost:8080/controller/method 就會返回(跳轉)到“ helloWorld.jsp ”頁面。

說到這了,順便說一下 @PathVariable 註解,其用來擷取請求路徑(url )中的動態參數。

頁面發出請求:

function login() {    var url = "${pageContext.request.contextPath}/person/login/";    var query = $(‘#id‘).val() + ‘/‘ + $(‘#name‘).val() + ‘/‘ + $(‘#status‘).val();    url += query;    $.get(url, function(data) {        alert("id: " + data.id + "name: " + data.name + "status: "                + data.status);    });}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

例如:

/*** @RequestMapping(value = "user/login/{id}/{name}/{status}") 中的 {id}/{name}/{status}* 與 @PathVariable int id、@PathVariable String name、@PathVariable boolean status* 一一對應,按名匹配。*/@RequestMapping(value = "user/login/{id}/{name}/{status}")@ResponseBody//@PathVariable註解下的資料類型均可用public User login(@PathVariable int id, @PathVariable String name, @PathVariable boolean status) {//返回一個User對象響應ajax的請求    return new User(id, name, status);}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
@ResponseBody

@Responsebody 註解表示該方法的返回的結果直接寫入 HTTP 響應本文(ResponseBody)中,一般在非同步擷取資料時使用,通常是在使用 @RequestMapping 後,傳回值通常解析為跳轉路徑,加上 @Responsebody 後返回結果不會被解析為跳轉路徑,而是直接寫入HTTP 響應本文中。 
作用: 
該註解用於將Controller的方法返回的對象,通過適當的HttpMessageConverter轉換為指定格式後,寫入到Response對象的body資料區。 
使用時機: 
返回的資料不是html標籤的頁面,而是其他某種格式的資料時(如json、xml等)使用;

當頁面發出非同步請求:

function login() {    var datas = ‘{"username":"‘ + $(‘#username‘).val() + ‘","userid":"‘ + $(‘#userid‘).val() + ‘","status":"‘ + $(‘#status‘).val() + ‘"}‘;    $.ajax({        type : ‘POST‘,        contentType : ‘application/json‘,        url : "${pageContext.request.contextPath}/user/login",        processData : false,        dataType : ‘json‘,        data : datas,        success : function(data) {            alert("userid: " + data.userid + "username: " + data.username + "status: "+ data.status);        },        error : function(XMLHttpRequest, textStatus, errorThrown) {            alert("出現異常,異常資訊:"+textStatus,"error");        }    });};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

例如:

@RequestMapping(value = "user/login")@ResponseBody// 將ajax(datas)發出的請求寫入 User 對象中,返回json對象響應回去public User login(User user) {       User user = new User();    user .setUserid(1);    user .setUsername("MrF");    user .setStatus("1");    return user ;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

非同步擷取 json 資料,加上 @Responsebody 註解後,就會直接返回 json 資料。

@RequestBody

@RequestBody 註解則是將 HTTP 要求本文插入方法中,使用適合的 HttpMessageConverter 將請求體寫入某個對象。

作用:

1) 該註解用於讀取Request請求的body部分資料,使用系統預設配置的HttpMessageConverter進行解析,然後把相應的資料繫結到要返回的對象上; 
2) 再把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指定;

例如:

@RequestMapping(value = "user/login")@ResponseBody// 將ajax(datas)發出的請求寫入 User 對象中public User login(@RequestBody User user) {   // 這樣就不會再被解析為跳轉路徑,而是直接將user對象寫入 HTTP 響應本文中    return user;    }

淺談@RequestMapping @ResponseBody 和 @RequestBody 註解的用法與區別

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.