SpringMVC—对Ajax的处理(含 JSON 类型)(2)

这里编写了一个通用的类型转换器:用来转换形如: firstName=jack&lastName=lily&gender=1&foods=Steak&foods=Pizza&quote=Enter+your+favorite+quote!&education=Jr.High&tOfD=Day 到 Student 对象。/*** @author solverpeng* @create 2016-08-22-17:37 */public final class InjectUtil<T> {    private static final Logger LOGGER = LoggerFactory.getLogger(InjectUtil.class);    public static <T> T converter2Obj(String source, Class<T> tClass) {T t = null;        try {t = tClass.newInstance();Map<String, Object> params = new HashMap<String, Object>();            if(source != null && source.length() > 0) {String[] fields = source.split("&");                for(String field : fields) {String[] fieldKeyValue = field.split("\\=");String fieldKey = fieldKeyValue[0];String fieldValue = fieldKeyValue[1];                    if (params.containsKey(fieldKey)) {Object keyValueRetrieved = params.get(fieldKey);                        if (keyValueRetrieved instanceof String) {ArrayList<String> values = new ArrayList<>();values.add(keyValueRetrieved.toString());values.add(fieldValue);params.put(fieldKey, values);} else {((ArrayList<String>) keyValueRetrieved).add(fieldValue);}} else {params.put(fieldKey, fieldValue);}}}BeanUtils.populate(t, params);} catch(InstantiationException | IllegalAccessException | InvocationTargetException e) {e.printStackTrace();LOGGER.error("String convert to Bean failure!", e);}        return t;}}不要忘记在 SpringMVC 中添加自定义的转换器。e3:也可以在 handler 方法中来调用上面我编写的通用的类型转换器来完成解析。@RequestMapping("/testStudent")public String testStudent(@RequestParam("student") String studentStr, String amount) {System.out.println("studentStr:" + studentStr);System.out.println("amount:" + amount);    return "success";
}
说明:对于复杂数据来说,我们借助不了 SpringMVC,只能借助于第三方,或是自己来编写解析器来解析。★多表单一次提交表单数据:<form action="" method="post" id="form2">First Name:<input type="text" name="firstName" maxlength="12" size="12"/> <br/>Last Name:<input type="text" name="lastName" maxlength="36" size="12"/> <br/>Gender:<br/>Male:<input type="radio" name="gender" value="1"/><br/>Female:<input type="radio" name="gender" value="0"/><br/><%–Favorite Food:<br/>Steak:<input type="checkbox" name="foods" value="Steak"/><br/>Pizza:<input type="checkbox" name="foods" value="Pizza"/><br/>Chicken:<input type="checkbox" name="foods" value="Chicken"/><br/>–%><textarea wrap="physical" cols="20" name="quote" rows="5">Enter your favorite quote!</textarea><br/>Select a Level of Education:<br/><select name="education"><option value="Jr.High">Jr.High</option><option value="HighSchool">HighSchool</option><option value="College">College</option></select><br/>Select your favorite time of day:<br/><select size="3" name="tOfD"><option value="Morning">Morning</option><option value="Day">Day</option><option value="Night">Night</option></select><p><input type="submit"/></p></form><form action="" method="post" id="form1">First Name:<input type="text" name="firstName" maxlength="12" size="12"/> <br/>Last Name:<input type="text" name="lastName" maxlength="36" size="12"/> <br/>Gender:<br/>Male:<input type="radio" name="gender" value="1"/><br/>Female:<input type="radio" name="gender" value="0"/><br/><%– Favorite Food:<br/>Steak:<input type="checkbox" name="foods" value="Steak"/><br/>Pizza:<input type="checkbox" name="foods" value="Pizza"/><br/>Chicken:<input type="checkbox" name="foods" value="Chicken"/><br/>–%><textarea wrap="physical" cols="20" name="quote" rows="5">Enter your favorite quote!</textarea><br/>Select a Level of Education:<br/><select name="education"><option value="Jr.High">Jr.High</option><option value="HighSchool">HighSchool</option><option value="College">College</option></select><br/>Select your favorite time of day:<br/><select size="3" name="tOfD"><option value="Morning">Morning</option><option value="Day">Day</option><option value="Night">Night</option></select></form>
e1:同时需要定义一个 Students 类:public class Students {    private List<Student> students;    public List<Student> getStudents() {        return students;}    public void setStudents(List<Student> students) {        this.students = students;}
}请求:$('form').submit(function() {$.ajax({url : "testStudent",data : JSON.stringify({            "students": [$('#form1').serializeObject(),$('#form2').serializeObject()]}),contentType:"application/json;charset=utf-8",type : "post",success : function (result) {console.log(result);}});    return false;
});handler 方法:@RequestMapping("/testStudent")public String testStudent(@RequestBody Students students) {    for(Student student : students.getStudents()) {System.out.println("student:" + student);}    return "success";
}可以正常打印。 e2:不额外增加类,即不定义 Students请求:$('form').submit(function() {$.ajax({url : "testStudent",data : JSON.stringify([$('#form1').serializeObject(),$('#form2').serializeObject()]),contentType:"application/json;charset=utf-8",type : "post",success : function (result) {console.log(result);}});    return false;
});handler 方法:e21:通过数组来接收@RequestMapping("/testStudent")public String testStudent(@RequestBody Student[] students) {    for(Student student : students) {System.out.println("student: " + student);}    return "success";
}e22:通过 List 来接收@RequestMapping("/testStudent")public String testStudent(@RequestBody List<Student> students) {   for(Student student : students) {System.out.println("student: " + student);}   return "success";
}★一个表单多个对象表单对象如:e1:<form action="" method="post" id="form">First Name:<input type="text" name="firstName" maxlength="12" size="12"/> <br/>Last Name:<input type="text" name="lastName" maxlength="36" size="12"/> <br/>Gender:<br/>Male:<input type="radio" name="gender" value="1"/><br/>Female:<input type="radio" name="gender" value="0"/><br/><%–Favorite Food:<br/>Steak:<input type="checkbox" name="foods" value="Steak"/><br/>Pizza:<input type="checkbox" name="foods" value="Pizza"/><br/>Chicken:<input type="checkbox" name="foods" value="Chicken"/><br/>–%><textarea wrap="physical" cols="20" name="quote" rows="5">Enter your favorite quote!</textarea><br/>Select a Level of Education:<br/><select name="education"><option value="Jr.High">Jr.High</option><option value="HighSchool">HighSchool</option><option value="College">College</option></select><br/>Select your favorite time of day:<br/><select size="3" name="tOfD"><option value="Morning">Morning</option><option value="Day">Day</option><option value="Night">Night</option></select>First Name:<input type="text" name="firstName" maxlength="12" size="12"/> <br/>Last Name:<input type="text" name="lastName" maxlength="36" size="12"/> <br/>Gender:<br/>Male:<input type="radio" name="gender" value="1"/><br/>Female:<input type="radio" name="gender" value="0"/><br/><%– Favorite Food:<br/>Steak:<input type="checkbox" name="foods" value="Steak"/><br/>Pizza:<input type="checkbox" name="foods" value="Pizza"/><br/>Chicken:<input type="checkbox" name="foods" value="Chicken"/><br/>–%><textarea wrap="physical" cols="20" name="quote" rows="5">Enter your favorite quote!</textarea><br/>Select a Level of Education:<br/><select name="education"><option value="Jr.High">Jr.High</option><option value="HighSchool">HighSchool</option><option value="College">College</option></select><br/>Select your favorite time of day:<br/><select size="3" name="tOfD"><option value="Morning">Morning</option><option value="Day">Day</option><option value="Night">Night</option></select><p><input type="submit"/></p></form>e2:<form action="" method="post">First Name:<input type="text" name="firstName[0]" maxlength="12" size="12"/> <br/>Last Name:<input type="text" name="lastName[0]" maxlength="36" size="12"/> <br/>Gender:<br/>Male:<input type="radio" name="gender[0]" value="1"/><br/>Female:<input type="radio" name="gender[0]" value="0"/><br/>Favorite Food:<br/>Steak:<input type="checkbox" name="foods[0]" value="Steak"/><br/>Pizza:<input type="checkbox" name="foods[0]" value="Pizza"/><br/>Chicken:<input type="checkbox" name="foods[0]" value="Chicken"/><br/><textarea wrap="physical" cols="20" name="quote[0]" rows="5">Enter your favorite quote!</textarea><br/>Select a Level of Education:<br/><select name="education[0]"><option value="Jr.High">Jr.High</option><option value="HighSchool">HighSchool</option><option value="College">College</option></select><br/>Select your favorite time of day:<br/><select size="3" name="tOfD[0]"><option value="Morning">Morning</option><option value="Day">Day</option><option value="Night">Night</option></select>First Name:<input type="text" name="firstName[1]" maxlength="12" size="12"/> <br/>Last Name:<input type="text" name="lastName[1]" maxlength="36" size="12"/> <br/>Gender:<br/>Male:<input type="radio" name="gender[1]" value="1"/><br/>Female:<input type="radio" name="gender[1]" value="0"/><br/>Favorite Food:<br/>Steak:<input type="checkbox" name="foods[1]" value="Steak"/><br/>Pizza:<input type="checkbox" name="foods[1]" value="Pizza"/><br/>Chicken:<input type="checkbox" name="foods[1]" value="Chicken"/><br/><textarea wrap="physical" cols="20" name="quote[1]" rows="5">Enter your favorite quote!</textarea><br/>Select a Level of Education:<br/><select name="education[1]"><option value="Jr.High">Jr.High</option><option value="HighSchool">HighSchool</option><option value="College">College</option></select><br/>Select your favorite time of day:<br/><select size="3" name="tOfD[1]"><option value="Morning">Morning</option><option value="Day">Day</option><option value="Night">Night</option></select><p><input type="submit"/></p></form>来看经过处理后的数据:e1:(1)JSON.stringify($('form').serializeObject()):{"firstName":["jack","tom"],"lastName":["aa","lily"],"foods":["Steak","Pizza","Steak"],"quote":["Enter your favorite quote!","Enter your favorite quote!"],"education":["Jr.High","Jr.High"],"tOfD":["Day","Day"],"gender":"1"}(2)$('form').serialize():firstName=jack&lastName=aa&foods=Steak&foods=Pizza&quote=Enter+your+favorite+quote!&education=Jr.High&tOfD=Day&firstName=tom&lastName=lily&gender=1&foods=Steak&quote=Enter+your+favorite+quote!&education=Jr.High&tOfD=Day说明:第一种是无法处理的,没办法分清数组中的值是属于哪个对象的。第二种方式可以处理,但是需要编写自定义的类型转换器,这里不进行说明。有兴趣的童鞋,请自行探索。e2:(1)JSON.stringify($('form').serializeObject()):{"firstName[0]":"aa","lastName[0]":"bb","gender[0]":"1","foods[0]":"Pizza","quote[0]":"Enter your favorite quote!","education[0]":"Jr.High","tOfD[0]":"Day","firstName[1]":"ds","lastName[1]":"cc","gender[1]":"1","foods[1]":["Steak","Pizza"],"quote[1]":"Enter your favorite quote!","education[1]":"Jr.High","tOfD[1]":"Day"}(2)$('form').serialize():firstName%5B0%5D=aa&lastName%5B0%5D=bb&gender%5B0%5D=1&foods%5B0%5D=Pizza&quote%5B0%5D=Enter+your+favorite+quote!&education%5B0%5D=Jr.High&tOfD%5B0%5D=Day&firstName%5B1%5D=ds&lastName%5B1%5D=cc&gender%5B1%5D=1&foods%5B1%5D=Steak&foods%5B1%5D=Pizza&quote%5B1%5D=Enter+your+favorite+quote!&education%5B1%5D=Jr.High&tOfD%5B1%5D=Day说明:第一种看着有规律可循,貌似可以进行解析,但是不是一个标准的 JSON 格式的数据。第二种甚至都出现了乱码,没有想到解析的办法。来看看第一种,同样这里提供一种思路,因为实现起来比较费劲。思路:使用正则like this :Gson gson = new Gson();
String jsonInString = "{\"student[0].firstName\": \"asdf\",\"student[0].lastName\": \"sfd\",\"student[0].gender\": \"1\",\"student[0].foods\":[\"Steak\",\"Pizza\"],\"student[0].quote\": \"Enter your favorite quote!\",\"student[0].education\": \"Jr.High\",\"student[0].tOfD\": \"Day\",\"student[1].firstName\": \"sf\",\"student[1].lastName\": \"sdf\",\"student[1].gender\": \"1\",\"student[1].foods\": [\"Pizza\",\"Chicken\"],\"student[1].quote\": \"Enter your favorite quote!\",\"student[1].education\": \"Jr.High\",\"student[1].tOfD\": \"Night\"}";
String jsonWithoutArrayIndices = jsonInString.replaceAll("\\[\\d\\]", "").replaceAll("student.","");
String jsonAsCollection = "[" + jsonWithoutArrayIndices + "]";
String jsonAsValidCollection = jsonAsCollection.replaceAll(",\"student.firstName\"","},{\"student.firstName\"");
System.out.println(jsonAsValidCollection);
Student[] students = gson.fromJson(jsonAsValidCollection, Student[].class);
System.out.println("-----------------------------------------------");
System.out.println(students[0]);
System.out.println("-----------------------------------------------");

  

转载于:https://www.cnblogs.com/ipetergo/p/6690537.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/252934.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

马来西亚热情拥抱阿里巴巴 马云倡议的eWTP首次落地海外

摘要&#xff1a;3月22日&#xff0c;马来西亚总理纳吉布与阿里巴巴集团董事局主席马云一同出现在吉隆坡一场盛大启动仪式上&#xff0c;他们将共同见证马云的eWTP理念落地马来西亚。 3月22日&#xff0c;在邀请阿里巴巴集团董事局主席马云、阿里巴巴集团CEO张勇、蚂蚁金服集团…

征名公布|Qtum量子链企业版—Unita 中文名征集圆满落幕

Qtum量子链基金会为感谢社区与为了充分调动社区积极性&#xff0c;调动社区力量&#xff0c;在Qtum企业版完整公布之前将中文名留给社区成员们集思广益&#xff0c;其中截止2018年11月26日&#xff0c;我们征集到数百份来自社区的优秀名称&#xff0c;在经过基金会层层严肃认真…

随便玩玩之PostgreSQL(第一章)PostgreSQL简介

随便玩玩之PostgreSQL 未经授权不得转载 第1章PostgreSQL简介 1.1什么是PostgreSQLPostgresql是数据库&#xff08;软件&#xff09;。The worlds most advanced open source database.世界上最先进的开源数据库。 1.2PostgreSQL的优势随便用、不要钱 比MySQL好&#xff0c;媲美…

bootstrap 利用jquery 添加disabled属性

添加&#xff1a; $("#id").attr("disabled","disabled"); 去除&#xff1a; $("#id").removeattr("disabled");转载于:https://www.cnblogs.com/duyunchao-2261/p/6692141.html

生产环境中Oracle常用函数总结

1>to_char,将日期转换为字符&#xff1b;add_months,在第一个参数的日期上加或者减第二个参数的值&#xff1b;select dkzh,jkhtbh,yhkrq,dkffrq,shqs,dqyqcs,to_char(add_months(dkffrq,shqsdqyqcs1),yyyymm) from grdk_dk_zz a where a.dkzt in(02,03) and jgbm like 01||…

国内VR内容分发平台探讨:未来充满变数,一切才刚开始

移动VR搞内容分发平台的思维源自于移动互联网时代&#xff0c;App Store成就了iPhone和苹果;安卓端谷歌应用商店称霸全球&#xff0c;唯独进不了中国&#xff0c;于是国内涌现了一大批移动分发平台&#xff0c;91无线、豌豆荚、安卓应用商店、机锋、安智、小米商店……最后大部…

Dockerfile构建容器镜像 - 运维笔记

在Docker的运用中&#xff0c;从下载镜像&#xff0c;启动容器&#xff0c;在容器中输入命令来运行程序&#xff0c;这些命令都是手工一条条往里输入的&#xff0c;无法重复利用&#xff0c;而且效率很低。所以就需要一 种文件或脚本&#xff0c;我们把想执行的操作以命令的方式…

201421123042 《Java程序设计》第8周学习总结

1. 本周学习总结 以你喜欢的方式&#xff08;思维导图或其他&#xff09;归纳总结集合相关内容。 2. 书面作业 1. ArrayList代码分析 1.1 解释ArrayList的contains源代码 源代码&#xff1a; 答&#xff1a;查找对象是否再数组中&#xff0c;并且返回在数组中的下标。如果不在数…

Linux驱动静态编译和动态编译方法详解

内核源码树的目录下都有两个文档Kconfig和Makefile。分布到各目录的Kconfig构成了一个分布式的内核配置数据库&#xff0c;每个Kconfig分别描述了所属目录源文档相关的内核配置菜单。在内核配置make menuconfig时&#xff0c;从Kconfig中读出菜单&#xff0c;用户选择后保存到.…

Linux学习-11月12日(Apache安装)

2019独角兽企业重金招聘Python工程师标准>>> 11.6 MariaDB安装 11.7/11.8/11.9 Apache安装 扩展 apache dso https://yq.aliyun.com/articles/6298 apache apxs https://wizardforcel.gitbooks.io/apache-doc/content/51.html apache工作模式 https://blog.csdn.…

11. sql DDL

SQL分为5大类&#xff1a; DDL:数据定义语言 DCL:数据控制语言 DML:数据操纵语言 DTL:数据事务语言 DQL:数据查询语言 1、DDL(data definition language):create,drop,alter,rename to 数据类型 ①、数字类型&#xff0c;可以数学运算 number&#xff08;4&#xff09;代表整数…

[bzoj2243][SDOI2011]染色

来自FallDream 的博客&#xff0c;未经允许&#xff0c;请勿转载&#xff0c;谢谢qaq 给定一棵有n个节点的无根树和m个操作&#xff0c;操作有2类&#xff1a; 1、将节点a到节点b路径上所有点都染成颜色c&#xff1b; 2、询问节点a到节点b路径上的颜色段数量&#xff08;连续相…

Linux学习笔记——例说makefile 增加宏定义

从学习C语言开始就慢慢开始接触makefile&#xff0c;查阅了很多的makefile的资料但总感觉没有真正掌握makefile&#xff0c;如果自己动手写一个makefile总觉得非常吃力。所以特意借助博客总结makefile的相关知识&#xff0c;通过例子说明makefile的具体用法。 例说makefile…

Android基本组件是什么?

1、ImageView继承View组件,不单单用于显示图片,用 XML代码 编写的Drawable也可以显示出来。其中的XML属性 android:scaleType(设置图片如何缩放或移动以适应ImageView的大小) 有很多的属性值,如:matrix(使用矩形方式进行缩放)fitXY(对图片横向纵向缩放)center(图片放在ImageVie…

Java 运算符及优先级

运算符 分割符&#xff1a;  ,  ;  []  ()算数运算符&#xff1a;    -  *  /  %    --关系运算符&#xff1a;  >  <  >  <    !逻辑运算符&#xff1a;  !  &  |  ^  &&  ||赋值运算符&#xff1a; …

array sort - 2 : quick sort

递归实现&#xff1a; #include <stdio.h>int arr[10] {3, 2, 4, 1, 9, 7, 5, 6, 0, 8};void print_array(){ int i 0; for (i 0; i < 10; i) printf("arr[%d]:%d ", i, arr[i]); printf("\n");}void swap(int *i, int *j){ …

Linux C 读取文件夹下所有文件(包括子文件夹)的文件名

本文&#xff1a;http://www.cnblogs.com/xudong-bupt/p/3504442.html Linux C 下面读取文件夹要用到结构体struct dirent&#xff0c;在头#include <dirent.h>中&#xff0c;如下&#xff1a; #include <dirent.h> struct dirent {long d_ino; /* inode number 索…

报表工具实现单据套打

【摘要】 单据套打再也不用手动测量&#xff0c;反复调试了&#xff0c;报表工具实现单据套打&#xff0c;去乾学院看个究竟&#xff1a;报表工具实现单据套打!实际项目开发中&#xff0c;很多情况会涉及到单据的打印。即在一张印刷好的空白单据上&#xff0c;准确无误地打印上…

每隔10秒钟打印一个“Helloworld”

/*** 每隔10秒钟打印一个“Helloworld”*/ public class Test03 {public static void main(String[] args) throws InterruptedException {ThreadImp threadImp new ThreadImp();Thread thread1 new Thread(threadImp);thread1.start();} }class ThreadImp extends Thread {p…

C++ STL 优先队列

//优先队列//Priority_queue //STL#include<iostream>#include<cstdio>#include<cstdlib>#include<queue>using namespace std;struct cmp{ bool operator() (const int a,const int b) const{//用const定义的a,b是包裹着变量外衣的常数&#xff0c;不…