昆明java培训
达内昆明广州春城路

18487146383

热门课程

知识点结论

  • 时间:2016-08-31
  • 发布:昆明Java培训
  • 来源:达内新闻

昆明Java培训机构的老师按之前的知识点说一下结论:

不能对这样的数据,指定"contentType:application/json",否则后端SpringMVC或者第三方的Jar包不能进行自动的解析,增加了解析的复杂度,所以将json串传入后台,在后台进行解析。

e1:serializeObject()

请求:

$(function() {

$('form').submit(function() {

$.ajax({

url : "testStudent",

data : {

amount : $("#amount").text(),

student : JSON.stringify($('form').serializeObject())

},

type : "post",

success : function (result) {

console.log(result);

}

});

return false;

});

});

后端处理:使用第三方工具类进行解析

@RequestMapping("/testStudent")

public String testStudent(@RequestParam("student") String studentStr, String amount) {

Student student = JsonUtil.fromJson(studentStr, Student.class);

System.out.println("student:" + student);

System.out.println("amount:" + amount);

return "success";

}

可以正常打印。

e2:serialize()

请求:

$(function() {

$('form').submit(function() {

$.ajax({

url : "testStudent",

data : {

amount : $("#amount").text(),

student : $('form').serialize()

},

type : "post",

success : function (result) {

console.log(result);

}

});

return false;

});

});

Handler方法:

e1:尝试让SpringMVC来解析:

@RequestMapping("/testStudent")

public String testStudent(@RequestParam("student") Student student, String amount) {

System.out.println("student:" + student);

System.out.println("amount:" + amount);

return "success";

}

结果:请求无法到达handler方法

e2:

@RequestMapping("/testStudent")

public String testStudent(Student student, String amount) {

System.out.println("student:" + student);

System.out.println("amount:" + amount);

return "success";

}

结果:请求可以正常到达目标Handler方法,但是无法映射Student对象。

方案:自己解析,编写自定义的类型转换器:

public class String2StudentConverter implements Converter<String, Student>{

@Override

public Student convert(String source) {

return InjectUtil.convert2Obj(source, Student.class);

}

}

这里我编写了一个通用的类型转换器:

用来转换形如:

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 = ew 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,只能借助于第三方,或是自己来编写解析器来解析。

★多表单一次提交

表单数据:

View Code

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:

View Code

e2:

View Code

来看经过处理后的数据:

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("-----------------------------------------------");

总结:

上面这部分,介绍了项目中遇到的绝大部分SpringMVC处理Ajax的问题,也提供了多种方案进行选择,对于不常见的问题,也给出了思路。是这篇文章最重要的部分。

学Java开发就到昆明达内Java培训班!了解详情请登陆昆明达内Java培训官网(km.Java.tedu.cn)!

上一篇:基于表单的Ajax提交
下一篇:JSON类型的字符串

iPhone摄像头发展史一步一个脚印

腾讯游戏Switch独立销量领先——昆明达内

达内java语言编程学以致用

苹果技术:A11芯片上新菜【达内培训】

选择城市和中心
贵州省

广西省

海南省