https://blog.csdn.net/u014079773/article/details/77720738

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

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

          maven+mysql

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

配置spring-servlet.xml:


 
 
  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-8 </value>
  12. <value>text/html;charset=UTF-8 </value>
  13. </list>
  14. </property>
  15. </bean>
配置:ApplicationContext.xml


 
 

  
  
  1. <!-- springmvc返回支持json类型 -->
  2. <bean id="mappingJacksonHttpMessageConverter"
  3. class= "org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" >
  4. <property name="supportedMediaTypes">
  5. <list>
  6. <value>application/json;charset=UTF-8 </value>
  7. <value>text/html;charset=UTF-8 </value>
  8. </list>
  9. </property>
  10. </bean>

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


 
 
  1. <dependency>
  2. <groupId>com.alibaba </groupId>
  3. <artifactId>fastjson </artifactId>
  4. <version>1.2.3 </version>
  5. </dependency>
jsp页面数据:


jsp发送ajax要求:


 
 
  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. } else {
  42. if($(upHotSearchId).val()!= ""){
  43. showTipAlert( "修改失败!!");
  44. } else{
  45. showTipAlert( "添加失败!!");
  46. }
  47. }
  48. }
  49. });

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


 
 
  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. if(StringUtils.isNotEmpty(createArr)){
  21. JSONArray createArray=JSONArray.parseArray(createArr);
  22. for( int i= 0;i<createArray.size();i++){
  23. Long tempId=JSONObject.parseObject(JSONObject.toJSONString(createArray.get(i))).getLong( "tempId");
  24. String keyword=JSONObject.parseObject(JSONObject.toJSONString(createArray.get(i))).getString( "keyword");
  25. Integer sort=JSONObject.parseObject(JSONObject.toJSONString(createArray.get(i))).getInteger( "sort");
  26. //创建热门搜索对象
  27. HotSearch hotSearch= new HotSearch();
  28. hotSearch.setTempid(tempId);
  29. hotSearch.setKeyword(keyword);
  30. hotSearch.setSort(sort);
  31. hotSearch.setCreateDate( new Date());
  32. hotSearch.setDelFlag( "0");
  33. //添加热门搜索信息
  34. countAddHotSearch = hotSearchService.addHotSearchSelective(hotSearch);
  35. }
  36. }
  37. if(StringUtils.isNotEmpty(modifyArr)){
  38. JSONArray modifyArray=JSONArray.parseArray(modifyArr);
  39. for( int i= 0;i<modifyArray.size();i++){
  40. Long hotSearchId=JSONObject.parseObject(JSONObject.toJSONString(modifyArray.get(i))).getLong( "id");
  41. Long tempId=JSONObject.parseObject(JSONObject.toJSONString(modifyArray.get(i))).getLong( "tempId");
  42. String keyword=JSONObject.parseObject(JSONObject.toJSONString(modifyArray.get(i))).getString( "keyword");
  43. Integer sort=JSONObject.parseObject(JSONObject.toJSONString(modifyArray.get(i))).getInteger( "sort");
  44. //创建热门搜索对象
  45. HotSearch hotSearch= new HotSearch();
  46. hotSearch.setHotSearchId(hotSearchId);
  47. hotSearch.setTempid(tempId);
  48. hotSearch.setKeyword(keyword);
  49. hotSearch.setSort(sort);
  50. //修改热门搜索信息
  51. countEditHotSearch = hotSearchService.modifyHostSearchSelectiveById(hotSearch);
  52. }
  53. }
  54. //判断修改或者新增成功
  55. if(countAddHotSearch> 0 || countEditHotSearch> 0){
  56. count= 1;
  57. }
  58. return count;
  59. }
后台获得参数格式:


备注:

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




GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e 3 个月前
8c391e04 6 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐