@RequestBody
作用:
@RequestBody注解用于讀取http請(qǐng)求的內(nèi)容(字符串),通過(guò)springmvc提供的HttpMessageConverter接口將讀到的內(nèi)容轉(zhuǎn)換為json、xml等格式的數(shù)據(jù)并綁定到controller方法的參數(shù)上。
本例子應(yīng)用:
@RequestBody注解實(shí)現(xiàn)接收http請(qǐng)求的json數(shù)據(jù)蔑担,將json數(shù)據(jù)轉(zhuǎn)換為java對(duì)象
@ResponseBody
作用:
該注解用于將Controller的方法返回的對(duì)象浸船,通過(guò)HttpMessageConverter接口轉(zhuǎn)換為指定格式的數(shù)據(jù)如:json,xml等,通過(guò)Response響應(yīng)給客戶端
本例子應(yīng)用:
@ResponseBody注解實(shí)現(xiàn)將controller方法返回對(duì)象轉(zhuǎn)換為json響應(yīng)給客戶端
請(qǐng)求json蛾茉,響應(yīng)json實(shí)現(xiàn):
環(huán)境準(zhǔn)備
Springmvc默認(rèn)用MappingJacksonHttpMessageConverter對(duì)json數(shù)據(jù)進(jìn)行轉(zhuǎn)換权薯,需要加入jackson的包
配置json轉(zhuǎn)換器
在注解適配器中加入messageConverters
<!--注解適配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
</list>
</property>
</bean>```
注意:如果使用<mvc:annotation-driven /> 則不用定義上邊的內(nèi)容姑躲。
controller編寫(xiě)
// 商品修改提交json信息,響應(yīng)json信息
@RequestMapping("/editItemSubmit_RequestJson")
public @ResponseBody Items editItemSubmit_RequestJson(@RequestBody Items items) throws Exception {
System.out.println(items);
//itemService.saveItem(items);
return items;
}```
頁(yè)面js方法編寫(xiě):
引入 js:
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>
//請(qǐng)求json響應(yīng)json
function request_json(){
$.ajax({
type:"post",
url:"${pageContext.request.contextPath }/item/editItemSubmit_RequestJson.action",
contentType:"application/json;charset=utf-8",
data:'{"name":"測(cè)試商品","price":99.9}',
success:function(data){
alert(data);
}
});
}```
請(qǐng)key/value盟蚣,響應(yīng)json實(shí)現(xiàn):
表單默認(rèn)請(qǐng)求application/x-www-form-urlencoded格式的數(shù)據(jù)即key/value黍析,通常有post和get兩種方法,響應(yīng)json數(shù)據(jù)是為了方便客戶端處理屎开,實(shí)現(xiàn)如下:
環(huán)境準(zhǔn)備
同第一個(gè)例子
controller編寫(xiě)
// 商品修改提交阐枣,提交普通form表單數(shù)據(jù),響應(yīng)json
@RequestMapping("/editItemSubmit_ResponseJson")
public @ResponseBody Items editItemSubmit_ResponseJson(Items items) throws Exception {
System.out.println(items);
// itemService.saveItem(items);
return items;
}```
6.5.4.3 頁(yè)面js方法編寫(xiě):
function formsubmit(){
var user = " name=測(cè)試商品&price=99.9";
alert(user);
$.ajax(
{
type:'post',//這里改為get也可以正常執(zhí)行
url:'${pageContext.request.contextPath}/item/ editItemSubmit_RequestJson.action',
//ContentType沒(méi)指定將默認(rèn)為:application/x-www-form-urlencoded
data:user,
success:function(data){
alert(data.name);
}
}
)
}```
從上邊的js代碼看出奄抽,已去掉ContentType的定義蔼两,ContentType默認(rèn)為:application/x-www-form-urlencoded格式
實(shí)際開(kāi)發(fā)中常用第二種方法,請(qǐng)求key/value數(shù)據(jù)逞度,響應(yīng)json結(jié)果额划,方便客戶端對(duì)結(jié)果進(jìn)行解析。