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.pswp.cn/news/252934.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/252934.shtml
英文地址,請注明出處:http://en.pswp.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;不…