This article mainly introduces the relevant knowledge of data format conversion in Json in SpringMVC. Has very good reference value. Let’s take a look with the editor below
1 @RequestBody
##Function:
The @RequestBody annotation is used to read the content of the http request (String), and convert the read content into json and xml through the HttpMessageConverter interface provided by springmvc. Data in other formats and bound to the parameters of the controller method.
List.<a href="//m.sbmmt.com/wiki/1059.html" target="_blank">action</a>?id=1&name=zhangsan&age=12<a href="//m.sbmmt.com/java/java-Action.html" target="_blank"></a>
This example application :@RequestBody annotation implements receiving json data of http request and converting json data into java
object 2 @ResponseBody
Function: This annotation is used to convert the object returned by the Controller method into data in the specified format through the HttpMessageConverter interface, such as : json, xml, etc., respond to the client through Response
This example applies:@ResponseBody annotation realizes the object conversion returned by the controller method Respond to json to the client
3 Environment configuration##3.1 Jar package preparation
Springmvc By default, Map
pingJacksonHttpMessageConverter is used to convert json data. You need to add the jackson package, as follows: 3.2 springmvc.xml file Configuration in1) If the annotation driver
(configuration file, No extra configuration is required2) If there is no annotation driver configured, the following configuration is required (this method is not recommended)
<!--注解适配器 --> <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 . The preparation of Controller
@RequestMapping("/testJson.action") @ResponseBody public Items testJson (@RequestBody Items items) { return items; }
corresponds to the preparation of js in the
jsp
function jsonTest () { $.ajax({ type:"post", url:"${pageContext.request.contextPath}/item/testJson.action", contentType:"application/json;charset=utf-8", data:'{"name":"测试商品","price":99.9}', success:function (data) { alert(data.name); } }); }
The above is the detailed content of Detailed introduction to Json data format conversion in SpringMVC. For more information, please follow other related articles on the PHP Chinese website!