Spring MVC implements json interaction-requestBody and responseBody

Keywords: Java JSON JQuery Javascript

json data interaction

1. Why json data interaction

json data format is commonly used in interface calls and html pages. json format is relatively simple and easy to parse.

For example: web service interface, transmission of json data.

2. Spring MVC for json interaction



(1) Request json, output json, request is JSON string, so it is not convenient to convert the content of the request to JSON in the front page.

(2) Request key/value and output json. This method is commonly used.

3. Environmental preparation

3.1 Loading the jar package for json rotation

Spring MVC uses jackson's package for json transformation (@requestBody and @responseBody use the following package for json transformation), as follows:

jackson-core-asl-1.9.11.jar

jackson-mapper-asl-1.9.11.jar

@ RequestBody effect:

@ RequestBody annotations are used to read the content of http requests (strings). The read content is converted to data in json, xml and other formats through the HttpMessageConverter interface provided by spring MVC and bound to the parameters of the controller method.

This example applies:

@ RequestBody annotation implements receiving json data for http requests and converting json data into java objects

@ ResponseBody function:

This annotation is used to convert the object returned by the Controller method into data in specified format through HttpMessageConverter interface, such as json,xml, etc., and respond to the client through Response.

This example applies:

@ ResponseBody annotation implements the transformation of the controller method return object into a json response to the client

3.2 Configuration of json converter

Add message Converters to the annotation adapter

  1. <!--Annotation adapter -->  
  2.     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">  
  3.         <property name="messageConverters">  
  4.         <list>  
  5.         <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>  
  6.         </list>  
  7.         </property>  
  8.     </bean>  



Note: If you use <mvc: annotation-driven/>, you do not need to define the above content.

4.json interaction testing

4.1 Input json string, output json string

4.1.1 JSP page

json string is submitted by ajax of jquery, and the output json result is parsed.

Use jduery and don't forget to introduce jquery-1.4.4.min.js

  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>json Interaction test</title>  
  13.     <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>  
  14.     <script type="text/javascript">  
  15.         //The request is JSON and the output is json.
  16.         function reuqestJson(){  
  17.             $.ajax({  
  18.                 type:'post',  
  19.                 url:'${pageContext.request.contextPath }/requestJson.action',  
  20.                 contentType:'application/json;charset=utf-8',     
  21.                 //Data format is json string, commodity information.
  22.                 data:'{"name":"Mobile phone","price":999}',  
  23.                 success:function(data){//Returns the json result.
  24.                     alert(data);  
  25.                 }   
  26.             });  
  27.         }  
  28.     </script>  
  29.   
  30.   </head>  
  31.     
  32.   <body>  
  33.     <input type="button" onclick="reuqestJson()"  value="The request is json,The output is json"/>  
  34.   </body>  
  35. </html>  



4.1.2controller

  1. package cn.edu.hpu.ssm.controller;  
  2.   
  3. import org.springframework.stereotype.Controller;  
  4. import org.springframework.web.bind.annotation.RequestBody;  
  5. import org.springframework.web.bind.annotation.RequestMapping;  
  6. import org.springframework.web.bind.annotation.ResponseBody;  
  7.   
  8. import cn.edu.hpu.ssm.po.ItemsCustom;  
  9.   
  10. //json interaction test
  11. @Controller  
  12. public class JsonText {  
  13.       
  14.     //Request JSON (commodity information), output JSON (commodity information)
  15.     //@ RequestBody cascades json of the requested merchandise information into itemsCustom objects
  16.     //@ ResponseBody converts itemsCustom to json format output
  17.     @RequestMapping("/requestJson")  
  18.     public @ResponseBody ItemsCustom requestJson(@RequestBody ItemsCustom itemsCustom){  
  19.           
  20.         //@ ResponseBody converts itemsCustom to json format output
  21.         return itemsCustom;  
  22.     }  
  23. }  



4.1.3 Test results



4.2 Input key/value, output is json string

4.2.1 JSP page

jquery's ajax is used to submit the key/value string and parse the output json results.

  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.     <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" >  
  12.     <title>json Interaction test</title>  
  13.     <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>  
  14.     <script type="text/javascript">  
  15.         //The request is key/value and the output is json.
  16.         function responseJson(){  
  17.             $.ajax({  
  18.                     type:'post',  
  19.                     url:'${pageContext.request.contextPath }/responseJson.action',    
  20.                     //The request is key/value, and there is no need to specify contentType, because the default is the key/value type.
  21.                     //contentType:'application/json;charset=utf-8',   
  22.                     //Data format is json string, commodity information.
  23.                     data:'name=Mobile phone&price=999',  
  24.                     success:function(data){//Returns the json result.
  25.                         alert(data);  
  26.                     }   
  27.                 });  
  28.         }  
  29.     </script>  
  30.   
  31.   </head>  
  32.     
  33.   <body>  
  34.     <input type="button" onclick="requestJson()" value="The request is key/value,The output is json"/>  
  35.   </body>  
  36. </html>  



4.2.2controller

  1. package cn.edu.hpu.ssm.controller;  
  2.   
  3. import org.springframework.stereotype.Controller;  
  4. import org.springframework.web.bind.annotation.RequestBody;  
  5. import org.springframework.web.bind.annotation.RequestMapping;  
  6. import org.springframework.web.bind.annotation.ResponseBody;  
  7.   
  8. import cn.edu.hpu.ssm.po.ItemsCustom;  
  9.   
  10. //json interaction test
  11. @Controller  
  12. public class JsonText {  
  13.       
  14.     //Request key/value (commodity information), output JSON (commodity information)
  15.     @RequestMapping("/responseJson")  
  16.     public @ResponseBody ItemsCustom responseJson(ItemsCustom itemsCustom){  
  17.           
  18.         //@ ResponseBody converts itemsCustom to json format output
  19.         System.out.println("The name of the commodity came from the front desk.:"+itemsCustom.getName());  
  20.         return itemsCustom;  
  21.     }  
  22. }  



4.2.3 test

The background console output "the name of the product passed from the front desk: mobile phone", and look at http data to see the feedback of json data.

For reprinting, please indicate the source: http://www.lai18.com/content/505491.html

Posted by flash_78 on Thu, 18 Apr 2019 14:45:34 -0700