@ResponseBody的作用是把返回值直接写到HTTP response body里,而不返回具体页面,springMVC结合org.springframework. http.converter.json.MappingJacksonHttpMessageConverter 自动处理json
场景1.
java代码:
@ResponseBody
@RequestMapping(value="/ajaxgetGoods",method = RequestMethod.POST)
public List<GoodsDTO> ajaxgetGoods(@RequestParam("setCode") String setCode){
QueryExpress queryExpress = new QueryExpress();
PageRows<GoodsDTO> pageRows = null;
if(!StringUtil.isEmpty(setCode,true)) {
queryExpress.add(QueryCriterions.eq(GoodsField.SETCODE,setCode));
}
try {
pageRows = goodsWeblogic.queryGoodsDTOListByPage(queryExpress,null);
} catch (ServiceException e) {
e.printStackTrace();
}
return pageRows.getRows();
}
对应的jQuery代码:
function selectGoods(){
$.ajax({
type : "POST",
url : "${ctx}/goods/ajaxgetGoods1",
data : {
setCode:$("#setCode").val()
},
success : function(data){
console.log(data);
$("#referId").empty();
var strOption = "<option value='-1'>全部</option>";
$.each(data,function(i,val){
strOption += "<option value='"+val.goods.goodsBarCode+"'>"+val.goods.goodsName+"</option>";
});
$("#referId").html(strOption);
}
});
}
此时返回的是GoodsDTO
实体对象
如果将jQuery代码改为:
function selectGoods(){
$.ajax({
type : "POST",
url : "${ctx}/goods/ajaxgetGoods1",
data : {
setCode:$("#setCode").val()
},
<span style="color:#ff0000;">dataType : 'json',</span>
success : function(data){
console.log(data);
$("#referId").empty();
var strOption = "<option value='-1'>全部</option>";
$.each(data,function(i,val){
strOption += "<option value='"+val.goods.goodsBarCode+"'>"+val.goods.goodsName+"</option>";
});
$("#referId").html(strOption);
}
});
}
此时返回json对象数组
这说明@ResponseBody并不直接返回json,把返回值直接写到HTTP response body,但是如果有json请求,回自动处理
场景2.
@ResponseBody
@RequestMapping(value="/ajaxgetGoods1",method = RequestMethod.POST)
public String ajaxgetGoods1(@RequestParam("setCode") String setCode){
QueryExpress queryExpress = new QueryExpress();
PageRows<GoodsDTO> pageRows = null;
if(!StringUtil.isEmpty(setCode,true)) {
queryExpress.add(QueryCriterions.eq(GoodsField.SETCODE,setCode));
}
try {
pageRows = goodsWeblogic.queryGoodsDTOListByPage(queryExpress,null);
} catch (ServiceException e) {
e.printStackTrace();
}
return JsonMapper.nonEmptyMapper().toJson(pageRows.getRows()); // 转json串
}
对应的jQuery代码:
function selectGoods(){
$.ajax({
type : "POST",
url : "${ctx}/goods/ajaxgetGoods1",
data : {
setCode:$("#setCode").val()
},
success : function(data){
console.log(data);
<span style="color:#ff0000;">var resultMsg = eval('(' + data + ')');</span>
console.log(resultMsg);
$("#referId").empty();
var strOption = "<option value='-1'>全部</option>";
$.each(data,function(i,val){
strOption += "<option value='"+val.goods.goodsBarCode+"'>"+val.goods.goodsName+"</option>";
});
$("#referId").html(strOption);
}
});
}
先将集合通过MappingJacksonHttpMessageConverter转换成json串,然后用eval函数转换成json对象,感觉这种方式有点多此一举 因为在场景1中通过 dataType : 'json'
直接可以获取json对象 何必要 后台转json串前台再转json对象呢,个人感觉场景1靠springMvc自动根据类型处理比较省时省力!!!!