SpringMVC transmits data in JSON format
In the past two days, SpringMVC was used to transmit JSON data formats, which caused various major problems. However, it was a hard nut to crack and finally solved the problem. The record here is for your reference. If you have any questions, please correct them.
Two jar packages are required for passing JSON data formats in SpringMVC: com.springsource.org. codehaus. jackson-1.4.2.jar, com.springsource.org. codehaus. jackson. mapper-1.4.2.jar.
Object JavaBean: Person has three String-type attributes: tname, gender, and age. Here, we need to pay special attention to the fact that Person requires a non-argument constructor. Otherwise, code 415 error will occur.
Front-end ajax functions:
$. Ajax ({
Url: "ajaxs", // note that "/" cannot be added to the Request Path here; otherwise, error 400 may occur and the request path cannot be found.
Type: "POST ",
ContentType: "application/json", // if this item is not added, the 415 error code will appear.
DataType: "JSON ",
Data: JSON. stringify ({"tname": "Zhang San", "gender": "male", "age": "20"}), // The parameters I used at the beginning
{"Tname": "Zhang San", "gender": "male", "age": "20"}, the error 400 always appears, the data from the foreground to the background does not match
Success: function (data, status) {alert ("OK ");},
Error: function () {alert ("error ");},
Fail: function () {alert ("fail ");}
});
Background:
@ RequestMapping (value = "/ajaxs", method = RequestMethod. POST)
@ ResponseBody
Public Person ajax (@ RequestBody Person p)
{
P. setTname ("lisi ");
System. out. println ("OK ");
Return p;
}
Here I have to sigh the strength of SpringMVC. Only @ Requestbody and @ ResponseBody can be used to implement the transfer of javabean and JSON data formats. We may find on the Internet that some data converter and other things need to be configured when using spring MVC to transmit data in JSON format, but after spring mvc3.x, we only need one You can add various data converters.