json前后台交互(一)

业务:jsp页面ajax传递json字符串传递到后台,实现功能。

环境:springmvc+spring+mybatis+jsp+js+css

          maven+mysql

springmvc配置文件配置支持返回json数据:

配置spring-servlet.xml:

[html]  view plain  copy
  1. <bean  class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
  2.      <property name="messageConverters">  
  3.     <list>  
  4.         <ref bean="mappingJacksonHttpMessageConverter" />  
  5.     list>  
  6.     property>  
  7. bean>  
  8. <bean id="mappingJacksonHttpMessageConverter"    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" >  
  9.       <property name="supportedMediaTypes">  
  10.            <list>  
  11.                <value>application/json;charset=UTF-8value>  
  12.                <value>text/html;charset=UTF-8value>  
  13.            list>  
  14.        property>  
  15.  bean>    
配置:ApplicationContext.xml

[html]  view plain  copy
  1.   
[html]  view plain  copy
  1.       
  2.     <bean id="mappingJacksonHttpMessageConverter"    
  3.         class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" >  
  4.         <property name="supportedMediaTypes">  
  5.             <list>  
  6.                 <value>application/json;charset=UTF-8value>  
  7.                 <value>text/html;charset=UTF-8value>  
  8.             list>  
  9.         property>  
  10.     bean>  

pom.xml添加依赖:使用json版本:

[html]  view plain  copy
  1. <dependency>  
  2.       <groupId>com.alibabagroupId>  
  3.        <artifactId>fastjsonartifactId>  
  4.        <version>1.2.3version>  
  5. dependency>  
jsp页面数据:


jsp发送ajax要求:

[javascript]  view plain  copy
  1. var modifyArr = [];  
  2. var createArr = [];  
  3. for(var i=0;i<$(".hotid").length;i++){  
  4.         if($($(".hotid")[i]).html()!=""){  
  5.             var id = $($(".hotid")[i]).html();  
  6.             var keyword = $($(".hotid")[i]).parent().find("td:eq(2) input").val();  
  7.             var sort = $($(".hotid")[i]).parent().find("td:eq(4) input").val();  
  8.             var tempId = $("#tempId").val();  
  9.             modifyArr.push({"id":id,"keyword":keyword,"sort":sort,"tempId":tempId});//数据数组json对象数据  
  10.         }else{  
  11.             var id = $($(".hotid")[i]).html();  
  12.             var keyword = $($(".hotid")[i]).parent().find("td:eq(2) input").val();  
  13.             var sort = $($(".hotid")[i]).parent().find("td:eq(4) input").val();  
  14.             createArr.push({"id":id,"keyword":keyword,"sort":sort,"tempId":tempId});//封装数组json对象数据  
  15.         }  
  16. }  
  17.  var data = {} ;  
  18.  data["modifyArr"] = modifyArr;  
  19.  data["createArr"] = createArr;  
  20.  $.ajax({  
  21.     type: "POST",  
  22.     url: "servehotselectiveajax.htm?&CSRFToken="+$("#CSRFToken").val(),  
  23.     data: JSON.stringify(data),//必须  
  24.     contentType : "application/json;charsetset=UTF-8",//必须  
  25.     dataType:"json",//必须  
  26.     cache: true,  
  27.     async: false,  
  28.     error: function (request) {  
  29.           showTipAlert("Connection error");  
  30.     },  
  31.     success: function (data) {  
  32.         console.log(data);  
  33.         if (data == 1) {  
  34.            if($(upHotSearchId).val()!=null&&$(upHotSearchId).val()!=""){  
  35.                  showTipAlert("修改成功!!");  
  36.             }else{  
  37.                 showTipAlert("添加成功!!");  
  38.             }  
  39.             $(upHotClsBtn).click();  
  40.             showHotSearch();  
  41.   
  42.         } else {  
  43.            if($(upHotSearchId).val()!=""){  
  44.                  showTipAlert("修改失败!!");  
  45.              }else{  
  46.                  showTipAlert("添加失败!!");  
  47.              }  
  48.         }  
  49.     }  
  50.  });  

以上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数据

[java]  view plain  copy
  1. /** 
  2.      * 修改或者新增热门搜索 
  3.      * @param hotSearch 
  4.      * @param request 
  5.      * @return 
  6.      */  
  7.     @RequestMapping(value = "/servehotselectiveajax")  
  8.     @ResponseBody  
  9.     public int servehotselectiveajax(HttpServletRequest req,HttpServletResponse resp,@RequestBody JSONObject obj) {  
  10.         int count=0;  
  11.         int countAddHotSearch=0;  
  12.         int countEditHotSearch=0;  
  13.         LOGGER.info("data:"+obj.toJSONString());  
  14.         //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"}]}  
  15.         String data=obj.toJSONString();  
  16.         //解析json数据  
  17.         JSONObject json = JSON.parseObject(data);  
  18.         String createArr=json.getString("createArr");  
  19.         String modifyArr=json.getString("modifyArr");  
  20.           
  21.         if(StringUtils.isNotEmpty(createArr)){  
  22.             JSONArray createArray=JSONArray.parseArray(createArr);  
  23.             for(int i=0;i
  24.                 Long tempId=JSONObject.parseObject(JSONObject.toJSONString(createArray.get(i))).getLong("tempId");  
  25.                 String keyword=JSONObject.parseObject(JSONObject.toJSONString(createArray.get(i))).getString("keyword");  
  26.                 Integer sort=JSONObject.parseObject(JSONObject.toJSONString(createArray.get(i))).getInteger("sort");  
  27.                 //创建热门搜索对象  
  28.                 HotSearch hotSearch=new HotSearch();  
  29.                 hotSearch.setTempid(tempId);  
  30.                 hotSearch.setKeyword(keyword);  
  31.                 hotSearch.setSort(sort);  
  32.                 hotSearch.setCreateDate(new Date());  
  33.                 hotSearch.setDelFlag("0");  
  34.                 //添加热门搜索信息  
  35.                 countAddHotSearch = hotSearchService.addHotSearchSelective(hotSearch);         
  36.             }  
  37.         }  
  38.           
  39.         if(StringUtils.isNotEmpty(modifyArr)){  
  40.             JSONArray modifyArray=JSONArray.parseArray(modifyArr);  
  41.             for(int i=0;i
  42.                 Long hotSearchId=JSONObject.parseObject(JSONObject.toJSONString(modifyArray.get(i))).getLong("id");  
  43.                 Long tempId=JSONObject.parseObject(JSONObject.toJSONString(modifyArray.get(i))).getLong("tempId");  
  44.                 String keyword=JSONObject.parseObject(JSONObject.toJSONString(modifyArray.get(i))).getString("keyword");  
  45.                 Integer sort=JSONObject.parseObject(JSONObject.toJSONString(modifyArray.get(i))).getInteger("sort");  
  46.                 //创建热门搜索对象  
  47.                 HotSearch hotSearch=new HotSearch();  
  48.                 hotSearch.setHotSearchId(hotSearchId);  
  49.                 hotSearch.setTempid(tempId);  
  50.                 hotSearch.setKeyword(keyword);  
  51.                 hotSearch.setSort(sort);  
  52.                 //修改热门搜索信息  
  53.                 countEditHotSearch = hotSearchService.modifyHostSearchSelectiveById(hotSearch);     
  54.             }  
  55.         }  
  56.   
  57.         //判断修改或者新增成功  
  58.         if(countAddHotSearch>0 || countEditHotSearch>0){  
  59.             count=1;  
  60.         }  
  61.         return count;  
  62.     }  
后台获得参数格式:


备注:

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

json前后台交互(一)_第1张图片

json前后台交互(一)_第2张图片

json前后台交互(一)_第3张图片



你可能感兴趣的:(ajax,json,生活感悟,json,ajax)