SpringMVC如何接收application/json內容編碼類型的參數?


  在上代碼之前,有必要先說說@ResquestBody注解的含義:

  1、官方解釋如下:

Annotation indicating a method parameter 
should be bound to the body of the web request.
The body of the request is passed through an {@link HttpMessageConverter}
to resolve the method argument depending on the content type of the request.
意思大概是:用該注解標識的方法的參數,會和web請求體綁定。
http消息轉換器會根據content-type的設置將請求體解析,從而初始化該方法的參數。

  2、另外還需解釋一下使用的場景

GET、POST方式提交的請求:

Content-type:

1、application/x-www-form-urlencoded:@RequestBody不是必須加的

2、mutipart/form-data:@RequestBody不能處理這種格式

3、其他格式,比如application/json,application/xml等,必須使用@RequestBody來處理

PUT方式提交的請求:

以上1和3的場景都是必須使用@RequestBody來處理的,2場景也是不支持的

  3、前端代碼如下:(這里必須將JSON對象使用JSON.stringify()轉為JSON字符串再傳遞,否則后台接收不到值)

$.ajax({
    url:"../../Notice/LoadForm.do",
    type:"post",
    contentType:"application/json;charset=UTF-8",
    data:JSON.stringify({"id":"1","title":"標題"})
});

  4、后台接收代碼示例

@RequestMapping(value="Notice/LoadForm")
@ResponseBody
public ResultJO loadForm(@RequestBody Notice notice){

}

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM