Json data format conversion in SpringMVC, springmvcjson
1 @ RequestBody
Purpose:
@ RequestBody annotation is used to read the content (string) of an http request ), use the HttpMessageConverter interface provided by springmvc to convert the read content into json, xml, and other data and bind it to the parameters of the controller method.
List. action? Id = 1 & name = zhangsan & age = 12
Application in this example:
@ RequestBody annotation: receives json data from http requests and converts json data to java objects.
2 @ ResponseBody
Purpose:
This annotation is used to convert the objects returned by the Controller Method to data in the specified format, such as json and xml, through the HttpMessageConverter interface, and send a Response to the client through Response.
Application in this example:
@ ResponseBody: converts the returned object of the controller Method to json and returns the response to the client.
3. Environment Configuration
3.1 jar package preparation
Springmvc converts json data using MappingJacksonHttpMessageConverter by default. You need to add the jackson package as follows:
3.2 springmvc. xml file configuration
1) if the annotation Driver (<mvc: annotation-driven/>) is configured in the configuration file, no additional configuration is required.
2) If the annotation driver is not configured, the following configuration is required (this method is not recommended)
<! -- Annotation adapter -->
<Bean class ="Org. springframework. web. servlet. mvc. method. annotation. RequestMappingHandlerAdapter">
<Property name ="MessageConverters">
<List>
<Bean class ="Org. springframework. http. converter. json. MappingJacksonHttpMessageConverter"> </Bean>
</List>
</Property>
</Bean>
4. Write Controller
@ RequestMapping ("/testJson. action ")
@ ResponseBody
Public Items testJson (@ RequestBody Items items ){
Return items;
}
Corresponding jsp page js Compilation
Function jsonTest (){
$. Ajax ({
Type: "post ",
Url: "$ {pageContext. request. contextPath}/item/testJson. action ",
ContentType: "application/json; charset = UTF-8 ",
Data: '{"name": "test item", "price": 99.9 }',
Success: function (data ){
Alert (data. name );
}
});
}