SpringMVC+AJAX+JSON
在做一个ajax发送json到springmvc的控制层,控制层的对象中有一个List集合,ajax调用总是报415错误。发现了一个一直没有注意到的问题,借机记录一下。
(细节部分都忽略了,在最后的demo项目地址中会有。这里只写主要的步骤)
一、添加pom.xml依赖
springmvc的pom.xml依赖在demo工程里都有,这里主要强调要添加以下两个依赖,否则@RequestBody和@ResponseBody这两个注解就不起作用。
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.jaxrs</groupId> <artifactId>jackson-jaxrs-json-provider</artifactId> <version>2.5.4</version> </dependency>
二、Controller层
package org.hope.lee.controller; import org.hope.lee.model.User; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.alibaba.fastjson.JSONObject; @Controller @RequestMapping("/user") public class UserController { @RequestMapping("index") public ModelAndView toAddUserPage() { return new ModelAndView("addUser"); } @RequestMapping(value = "/add",method = RequestMethod.POST) @ResponseBody public ResponseEntity<String> addUser(@RequestBody User user) { JSONObject object = new JSONObject(); object.put("success", "成功"); return new ResponseEntity<>(object.toString(), HttpStatus.OK); } }
三、JSP页面
注意"②"处的代码,这种方式传递list参数给controller层种的@RequestBody对象是会报415错误的。我发现是因为"②"处addresses的value会多一个双引号
{"name":"李四","age":"59","gender":"男","addresses":"[{\"addressName\":\"A区\"},{\"addressName\":\"B区\"}]"}。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="../static/js/jquery-1.11.0.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#btn").click(function() { var vname = $('#name').val(); var vage = $('#age').val(); var vgender = $("input[name='gender']:checked").val(); var checkedParams = $("input:checkbox:checked"); checked_val = []; for(k in checkedParams){ if(checkedParams[k].checked) checked_val.push(checkedParams[k].value); }; var arr = new Array(); for(var i = 0; i < checked_val.length; i++) { arr.push({'addressName':checked_val[i]}); } var arrs = JSON.stringify(arr); var params = { name : vname, age : vage, gender : vgender, addresses:arrs } var params2 = '{"name":\"'+vname+'\","age":'+vage+',"gender":\"'+vgender+'\","addresses":'+arrs+'}' //如果有更好的办法,希望给我留言。 console.log("params=" + JSON.stringify(params)); console.log("params2=" + params2); $.ajax({ url : "add", type : 'POST', data : params2, //① //data:JSON.stringify(params), //② dataType : 'json', contentType : "application/json;charset=utf-8", beforeSend: function() { }, success : function(data) { alert("保存成功"); }, error : function(XMLHttpRequest, textStatus, errorThrown) { console.log(textStatus + "服务器异常,请稍后尝试!"); } }); }); }); </script> </head> <body> 姓名:<input type="text" id="name" /><br/> 年龄:<input type="text" id="age" /><br/> 性别: 男:<input type="radio" checked="checked" name="gender" value="男"/> 女:<input type="radio" name="gender" value="女"/><br/> 地址: A区<input type="checkbox" id="checkbox" value="A区" /> B区<input type="checkbox" id="checkbox" value="B区" /> C区<input type="checkbox" id="checkbox" value="B区" /><br/> <button id="btn" >保存</button> </body> </html>
https://gitee.com/huayicompany/spring-learn/tree/master/springmvc-json