SpringMVC将表单对象序列化成Json字符串提交,以List接收

出自:http://blog.csdn.net/m0_37595732/article/details/71440853

HTML

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>submitUserList_4</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script language="JavaScript" src="${ctx }/js/jquery-3.1.1.min.js" ></script>
<script language="JavaScript" src="${ctx }/js/parseJson.js" ></script>
<script type="text/javascript" language="JavaScript">
//将表单序列化成json格式的数据(但不适用于含有控件的表单,例如复选框、多选的select) function submitUserList_4() {alert("ok");
var jsonStr = $("#form1").
serializeJson();
//console.log("jsonStr:\r\n" + jsonStr);
//alert(jsonStr);
$.ajax({
url : "${ctx}/test/getJsList",
type : "POST",
contentType : 'application/json;charset=utf-8', //设置请求头信息
dataType : "json",
data : jsonStr,
success : function(data) {
alert(data);
},
error : function(res) {
alert(res.responseText);
}
});
}
</script>
</head> <body>
<h1>submitUserList_4</h1>
<form id="form1">
age:<input type="text" name="age" value="11"><br/>
name:<input type="text" name="name" value="jack"><br/>
sex:<input type="text" name="sex" value="男"><br/><br/> age:<input type="text" name="age" value="12"><br/>
name:<input type="text" name="name" value="rose"><br/>
sex:<input type="text" name="sex" value="女"><br/><br/> <input type="button" value="submit" onclick="submitUserList_4();">
</form>
</body>
</html>

Java

@RequestMapping(value = "/submitUserList_4", method={RequestMethod.POST})
@ResponseBody
public String submitUserList_4(@RequestBody List<User> users)
throws Exception{
String result = "";
if(users == null || users.size() <= 0){ return "No any ID.中文"; }
result = this.showUserList(users);
return result;
}

启动SpringMVC的注解功能,完成请求和注解POJO的映射

<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<context:component-scan base-package="com.leon" />
<!--避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->
</list>
</property>
</bean>

POM

<!-- 映入JSON -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>

js

$.fn.serializeJson = function(){
var jsonData1 = {};
var serializeArray = this.serializeArray();
// 先转换成{"id": ["12","14"], "name": ["aaa","bbb"], "pwd":["pwd1","pwd2"]}这种形式
$(serializeArray).each(function () {
if (jsonData1[this.name]) {
if ($.isArray(jsonData1[this.name])) {
jsonData1[this.name].push(this.value);
} else {
jsonData1[this.name] = [jsonData1[this.name], this.value];
}
} else {
jsonData1[this.name] = this.value;
}
});
// 再转成[{"id": "12", "name": "aaa", "pwd":"pwd1"},{"id": "14", "name": "bb", "pwd":"pwd2"}]的形式
var vCount = 0;
// 计算json内部的数组最大长度
for(var item in jsonData1){
var tmp = $.isArray(jsonData1[item]) ? jsonData1[item].length : 1;
vCount = (tmp > vCount) ? tmp : vCount;
} if(vCount > 1) {
var jsonData2 = new Array();
for(var i = 0; i < vCount; i++){
var jsonObj = {};
for(var item in jsonData1) {
jsonObj[item] = jsonData1[item][i];
}
jsonData2.push(jsonObj);
}
return JSON.stringify(jsonData2);
}else{
return "[" + JSON.stringify(jsonData1) + "]";
}
};

修改的js,返回json的数组对象

$.fn.serializeJson = function(){
var jsonData1 = {};
var serializeArray = this.serializeArray();
// 先转换成Object{id:Array(2),name:Array(2),pwd:Array(2)}==>{"id": ["12","14"], "name": ["aaa","bbb"], "pwd":["pwd1","pwd2"]}这种形式,即属性数组形式
$(serializeArray).each(function () {
if (jsonData1[this.name]) {
if ($.isArray(jsonData1[this.name])) {
jsonData1[this.name].push(this.value);
} else {
jsonData1[this.name] = [jsonData1[this.name], this.value];
}
} else {
jsonData1[this.name] = this.value;
}
});
// 再转成[Object,Object]==>[{"id": "12", "name": "aaa", "pwd":"pwd1"},{"id": "14", "name": "bb", "pwd":"pwd2"}]的形式,即对象数组
var vCount = 0;
// 计算json内部的数组最大长度
for(var item in jsonData1){
var tmp = $.isArray(jsonData1[item]) ? jsonData1[item].length : 1;
vCount = (tmp > vCount) ? tmp : vCount;
}
var jsonData2 = new Array();
if(vCount > 1) {
for(var i = 0; i < vCount; i++){
var jsonObj = {};
for(var item in jsonData1) {
jsonObj[item] = jsonData1[item][i];
}
jsonData2.push(jsonObj);
}
}else{
jsonData2.push(jsonData1);
}
return jsonData2;//返回的是json的对象数组
};

总结:最关键的是JS中的拼接json数据,ajax请求的属性以及后台接收的参数

上一篇:面向对象程序设计-C++_课时12访问限制


下一篇:IOS开发之把 Array 和 Dictionaries 序列化成 JSON 对象