SpringMVC—对Ajax的处理(含 JSON 类型)
Posted Ipeter
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringMVC—对Ajax的处理(含 JSON 类型)相关的知识,希望对你有一定的参考价值。
这里编写了一个通用的类型转换器: 用来转换形如: firstName=jack&lastName=lily&gender=1&foods=Steak&foods=Pizza"e=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"e=Enter+your+favorite+quote!&education=Jr.High&tOfD=Day&firstName=tom&lastName=lily&gender=1&foods=Steak"e=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"e%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"e%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("-----------------------------------------------");
以上是关于SpringMVC—对Ajax的处理(含 JSON 类型)的主要内容,如果未能解决你的问题,请参考以下文章
SpringMVC——对Ajax的处理(包含 JSON 类型)
Spring注解处理Ajax请求-JSON格式[系统架构:Spring+SpringMVC+MyBatis+MySql]