业务: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-8value>
- <value>text/html;charset=UTF-8value>
- list>
- property>
- bean>
配置:ApplicationContext.xml
-
- <bean id="mappingJacksonHttpMessageConverter"
- class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" >
- <property name="supportedMediaTypes">
- <list>
- <value>application/json;charset=UTF-8value>
- <value>text/html;charset=UTF-8value>
- list>
- property>
- bean>
pom.xml添加依赖:使用json版本:
- <dependency>
- <groupId>com.alibabagroupId>
- <artifactId>fastjsonartifactId>
- <version>1.2.3version>
- 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});
- }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});
- }
- }
- 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数据
-
-
-
-
-
-
- @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());
-
- String data=obj.toJSONString();
-
- 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
- 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
- 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