Java后台如何接收并处理前台传过来的json格式的数组参数
业务:jsp页面ajax传递json字符串传递到后台,实现功能。
环境:springmvc+spring+mybatis+jsp+js+css
maven+mysql
springmvc配置文件配置支持返回json数据:
配置spring-servlet.xml:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" >
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
配置:ApplicationContext.xml
<!-- springmvc返回支持json类型 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" >
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
pom.xml添加依赖:使用json版本:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.3</version>
</dependency>
jsp页面数据:
jsp发送ajax要求:
var modifyArr = [];
var createArr = [];
for(var i=0;i<$(".hotid").length;i++){
if($($(".hotid")[i]).html()!=""){
var id = $($(".hotid")[i]).html();
var keyword = $($(".hotid")[i]).parent().find("td:eq(2) input").val();
var sort = $($(".hotid")[i]).parent().find("td:eq(4) input").val();
var tempId = $("#tempId").val();
modifyArr.push({"id":id,"keyword":keyword,"sort":sort,"tempId":tempId});//数据数组json对象数据
}else{
var id = $($(".hotid")[i]).html();
var keyword = $($(".hotid")[i]).parent().find("td:eq(2) input").val();
var sort = $($(".hotid")[i]).parent().find("td:eq(4) input").val();
createArr.push({"id":id,"keyword":keyword,"sort":sort,"tempId":tempId});//封装数组json对象数据
}
}
var data = {} ;
data["modifyArr"] = modifyArr;
data["createArr"] = createArr;
$.ajax({
type: "POST",
url: "servehotselectiveajax.htm?&CSRFToken="+$("#CSRFToken").val(),
data: JSON.stringify(data),//必须
contentType : "application/json;charsetset=UTF-8",//必须
dataType:"json",//必须
cache: true,
async: false,
error: function (request) {
showTipAlert("Connection error");
},
success: function (data) {
console.log(data);
if (data == 1) {
if($(upHotSearchId).val()!=null&&$(upHotSearchId).val()!=""){
showTipAlert("修改成功!!");
}else{
showTipAlert("添加成功!!");
}
$(upHotClsBtn).click();
showHotSearch();
} else {
if($(upHotSearchId).val()!=""){
showTipAlert("修改失败!!");
}else{
showTipAlert("添加失败!!");
}
}
}
});
以上js代码数组数据:
var createArr=[{"id":"","keyword":"11","sort":"11","tempId":"21"}]
var modifyArr=[{"id":"205","keyword":"华为","sort":"2","tempId":"21"},{"id":"206","keyword":"游戏本","sort":"3","tempId":"21"},{"id":"207","keyword":"平板电视","sort":"3","tempId":"21"},{"id":"208","keyword":"连衣裙","sort":"4","tempId":"21"}]
备注:
1.data数据封装最好不要用{key:JSON.stringify(xx)}而用var data = {};data[key] = Oject;(必须)
2.data: JSON.stringify(data)将数组通过JSON.stringify()转换成json字符串(必须)
3.contentType : "application/json;charsetset=UTF-8"因为传递的是json数据只后台故这里需要设置文件类型(必须)
4.dataType:'json',指定数据类型为json
5.前台data数据格式:
后台controller:后台用RequstBody接受json数据
/**
* 修改或者新增热门搜索
* @param hotSearch
* @param request
* @return
*/
@RequestMapping(value = "/servehotselectiveajax")
@ResponseBody
public int servehotselectiveajax(HttpServletRequest req,HttpServletResponse resp,@RequestBody JSONObject obj) {
int count=0;
int countAddHotSearch=0;
int countEditHotSearch=0;
LOGGER.info("data:"+obj.toJSONString());
//data:{"createArr":[{"hotSearchId":"","keyword":"ss","sort":"5","tempid":"21"}],"modifyArr":[{"hotSearchId":"205","keyword":"华为","sort":"2","tempid":"21"},{"hotSearchId":"206","keyword":"游戏本","sort":"3","tempid":"21"},{"hotSearchId":"207","keyword":"平板电视","sort":"3","tempid":"21"},{"hotSearchId":"208","keyword":"连衣裙","sort":"4","tempid":"21"}]}
String data=obj.toJSONString();
//解析json数据
JSONObject json = JSON.parseObject(data);
String createArr=json.getString("createArr");
String modifyArr=json.getString("modifyArr");
if(StringUtils.isNotEmpty(createArr)){
JSONArray createArray=JSONArray.parseArray(createArr);
for(int i=0;i<createArray.size();i++){
Long tempId=JSONObject.parseObject(JSONObject.toJSONString(createArray.get(i))).getLong("tempId");
String keyword=JSONObject.parseObject(JSONObject.toJSONString(createArray.get(i))).getString("keyword");
Integer sort=JSONObject.parseObject(JSONObject.toJSONString(createArray.get(i))).getInteger("sort");
//创建热门搜索对象
HotSearch hotSearch=new HotSearch();
hotSearch.setTempid(tempId);
hotSearch.setKeyword(keyword);
hotSearch.setSort(sort);
hotSearch.setCreateDate(new Date());
hotSearch.setDelFlag("0");
//添加热门搜索信息
countAddHotSearch = hotSearchService.addHotSearchSelective(hotSearch);
}
}
if(StringUtils.isNotEmpty(modifyArr)){
JSONArray modifyArray=JSONArray.parseArray(modifyArr);
for(int i=0;i<modifyArray.size();i++){
Long hotSearchId=JSONObject.parseObject(JSONObject.toJSONString(modifyArray.get(i))).getLong("id");
Long tempId=JSONObject.parseObject(JSONObject.toJSONString(modifyArray.get(i))).getLong("tempId");
String keyword=JSONObject.parseObject(JSONObject.toJSONString(modifyArray.get(i))).getString("keyword");
Integer sort=JSONObject.parseObject(JSONObject.toJSONString(modifyArray.get(i))).getInteger("sort");
//创建热门搜索对象
HotSearch hotSearch=new HotSearch();
hotSearch.setHotSearchId(hotSearchId);
hotSearch.setTempid(tempId);
hotSearch.setKeyword(keyword);
hotSearch.setSort(sort);
//修改热门搜索信息
countEditHotSearch = hotSearchService.modifyHostSearchSelectiveById(hotSearch);
}
}
//判断修改或者新增成功
if(countAddHotSearch>0 || countEditHotSearch>0){
count=1;
}
return count;
}
后台获得参数格式:
备注:
1.注意获得的参数应该这样:
[{"hotSearchId":"","keyword":"ss","sort":"5","tempid":"21"}]而不是[{hotSearchId:,keyword:ss,sort:5,tempid:21}],json数据肯定包含引号,否则解析报错
2.后台获得的json数据:
data:{"createArr":[{"hotSearchId":"","keyword":"ss","sort":"5","tempid":"21"}],"modifyArr":[{"hotSearchId":"205","keyword":"华为","sort":"2","tempid":"21"},{"hotSearchId":"206","keyword":"游戏本","sort":"3","tempid":"21"},{"hotSearchId":"207","keyword":"平板电视","sort":"3","tempid":"21"},{"hotSearchId":"208","keyword":"连衣裙","sort":"4","tempid":"21"}]}
3.关于 @ResponseBody:
将内容或对象作为 HTTP 响应正文返回,使用@ResponseBody将会跳过视图处理部分,而是调用适合HttpMessageConverter,将返回值写入输出流。
4.关于@ResquestBody:
接收的是一个Json对象的字符串,而不是一个Json对象
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, 不能处理;
其他格式(其他格式包括application/json, application/xml等), 必须;
说明:request的body部分的数据编码格式由header部分的Content-Type指定;
故前台传递json数据时后台必须用@ResqustBody来处理,前台ajax必须指定contentType类型为 "application/json;charsetset=UTF-8",默认为application/x-www-form-urlencoded
---------------------
作者:陌上桑花开花
来源:CSDN
原文:https://blog.csdn.net/u014079773/article/details/77720738
版权声明:本文为博主原创文章,转载请附上博文链接!
更多推荐
所有评论(0)