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
SpringMVC+AJAX+JSON的更多相关文章
- springMvc+AJAX+JSON的增删改查
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"% ...
- Ajax json交互和SpringMVC中@RequestBody
Ajax json交互和SpringMVC中@RequestBody 标签: 背景 自己提供出去得接口中参数设置为@RequestBody VipPromotionLog vipPromotionLo ...
- AJAX发送json,SpringMVC 接收JSON,@RequestBody
需求:JQuery ajax前台,采用 POST请求 发送json,后台使用SpringMVC接收json并处理 前台: $.ajax({ url:"请求地址", type:&qu ...
- SpringMVC Ajax返回的请求json
的方式来解决在中国字符串乱码问题
1.org.springframework.http.converter.StringHttpMessageConverter类是类处理请求或相应的字符串.和默认字符集ISO-8859-1,所以当返回 ...
- SpringMVC学习--json
简介 json数据格式在接口调用中.html页面中较常用,json格式比较简单,解析还比较方便.比如:webservice接口,传输json数据. springmvc与json交互 @RequestB ...
- SpringMVC关于json、xml自动转换的原理研究[附带源码分析 --转
SpringMVC关于json.xml自动转换的原理研究[附带源码分析] 原文地址:http://www.cnblogs.com/fangjian0423/p/springMVC-xml-json-c ...
- springMvc中406错误解决,springMvc使用json出现406 (Not Acceptable)
springMvc中406错误解决, springMvc使用json出现406 (Not Acceptable) >>>>>>>>>>> ...
- Maven搭建SpringMVC+MyBatis+Json项目(多模块项目)
一.开发环境 Eclipse:eclipse-jee-luna-SR1a-win32; JDK:jdk-8u121-windows-i586.exe; MySql:MySQL Server 5.5; ...
- springMVC学习总结(四)springmvc处理json数据类型以及fastjson的使用
springMVC学习总结(四)springmvc处理json数据类型以及fastjson的使用 主要内容: 这篇文章主要是总结之前使用springmv接收json的时候遇到的问题,下面通过前台发送a ...
随机推荐
- UVa 12230 && HDU 3232 Crossing Rivers (数学期望水题)
题意:你要从A到B去上班,然而这中间有n条河,距离为d.给定这n条河离A的距离p,长度L,和船的移动速度v,求从A到B的时间的数学期望. 并且假设出门前每条船的位置是随机的,如果不是在端点,方向也是不 ...
- excel绝对引用中间添加符号
=F1&"_"&J1 绝对引用 相对引用 按F4 然后复制全部,选择性黏贴,值和数字即可
- python 编码方式大全 fr = open(filename_r,encoding='cp852')
7.8.3. Standard Encodings Python comes with a number of codecs built-in, either implemented as C fun ...
- 常见XML解析器
xpp3 官网 http://www.extreme.indiana.edu/xgws/xsoap/xpp/ 简介 Xml Pull Parser (in short XPP) is a stream ...
- Informatica增量抽取时间的设置
使用数据库或者系统变量的当前时间 Informatica中的$$SYSDATE是表示当前系统时间的系统变量. 通过这个变量,我们对每天抽取的数据可以使用以下表达式来实现增量抽取: 时间戳字段>= ...
- SpringMVC绑定到实体数组、list、set、和map时要注意
实体的属性前一定要用.分割,如果是使用jquery的ajax提交的一个js数组对象,则请求数据会被格式化为 var sub = [{name:1,num:2},{name:1,num:2}] $.po ...
- 使用jetty-maven-plugin运行maven多项目
1.准备工作 org.eclipse.jetty jetty-maven-plugin 9.2.11.v20150529 jdk 1.7 maven 3.1 2.采用maven管理多项目 ...
- Send or receive files via Xshell
1. install lrzsz $ sudo apt-get install lrzsz 2. If you want to send file from your pc to pi, just d ...
- MVC-1.1 BundleConfig-ScriptBundle
App_Start中的BudleCnfig.cs中 bundles.Add(new ScriptBundle("~/bundles/jquery").Include( " ...
- DBCC--SQLPERF
提供所有数据库的事务日志空间使用情况统计信息.也可以用于重置等待和闩锁的统计信息. 语法: DBCC SQLPERF ( [ LOGSPACE ] | [ "sys.dm_os_latch ...