標籤:handle 比較 first exce type size body catch params
這裡編寫了一個通用的類型轉換器:用來轉換形如: 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 類型)(2)