@RequestBody
作用:
@RequestBody注解用于讀取http請求的內(nèi)容(字符串),通過springmvc提供的HttpMessageConverter接口將讀到的內(nèi)容轉(zhuǎn)換為json、xml等格式的數(shù)據(jù)并綁定到controller方法的參數(shù)上。
本例子應(yīng)用:
@RequestBody注解實(shí)現(xiàn)接收http請求的json數(shù)據(jù),將json數(shù)據(jù)轉(zhuǎn)換為java對象
@ResponseBody
作用:
該注解用于將Controller的方法返回的對象,通過HttpMessageConverter接口轉(zhuǎn)換為指定格式的數(shù)據(jù)如:json,xml等,通過Response響應(yīng)給客戶端
本例子應(yīng)用:
@ResponseBody注解實(shí)現(xiàn)將controller方法返回對象轉(zhuǎn)換為json響應(yīng)給客戶端
請求json,響應(yīng)json實(shí)現(xiàn):
環(huán)境準(zhǔn)備
Springmvc默認(rèn)用MappingJacksonHttpMessageConverter對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編寫
// 商品修改提交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;
}```
頁面js方法編寫:
引入 js:
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>
//請求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":"測試商品","price":99.9}',
success:function(data){
alert(data);
}
});
}```
請key/value,響應(yīng)json實(shí)現(xiàn):
表單默認(rèn)請求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編寫
// 商品修改提交,提交普通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 頁面js方法編寫:
function formsubmit(){
var user = " name=測試商品&price=99.9";
alert(user);
$.ajax(
{
type:'post',//這里改為get也可以正常執(zhí)行
url:'${pageContext.request.contextPath}/item/ editItemSubmit_RequestJson.action',
//ContentType沒指定將默認(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í)際開發(fā)中常用第二種方法,請求key/value數(shù)據(jù),響應(yīng)json結(jié)果,方便客戶端對結(jié)果進(jìn)行解析。