SPRINGMVC Learning (10)--SPRINGMVC JSON data interaction with the foreground

Source: Internet
Author: User

JSON data format is commonly used in interface calls, HTML pages, JSON format is relatively simple, parsing is more convenient, so the use is very common. In Springmvc, the parsing and transformation of JSON data is also supported, and this article summarizes how JSON data interacts with the foreground in Springmvc.

Two forms of interaction

There are two main forms of springmvc and foreground interaction, as shown in:

Can be seen, the front-end transmission of the way there are two, one is to pass the data in JSON format, and the other is to pass the URL of the ordinary key/value string over, for these two ways, in the controller class will have different parsing, However, the JSON-formatted data returned in the controller class is the same. Here's a detailed analysis of how SPRINGMVC interacts with the foreground for JSON data. Recognize two annotations before you speak.

@RequestBody annotations

@RequestBody annotations are used to read the contents of an HTTP request (string), and the Httpmessageconverter interface provided by SPRINGMVC converts the read content to JSON, Data in a format such as XML and bound to the parameters of a controller class method.
This example applies: @RequestBody annotations implement JSON data to receive HTTP requests and convert JSON data to Java objects. As follows:

@ResponseBody annotations

The @ResponseBody annotation is used to convert the object returned by the Controller class method to the specified format data through the Httpmessageconverter interface, such as JSON, XML, etc., in response to the client through response.
This example applies: The @ResponseBody annotation implementation converts the Controller class method return object to a JSON response to the client, as follows:


After I have explained it in such detail, everyone must have realized the meaning of the two annotations. Well, here's a concrete analysis of how SPRINGMVC interacts with the foreground for JSON data.

Preparing the environment for loading the JSON jar package

SPRINGMVC the JSON data is converted by default with Mappingjacksonhttpmessageconverter and needs to be added to Jackson's package, And because SpringMVC3 and SpringMVC4 have a different jar package for JSON interaction, I'm using SpringMVC4, and I need to import the following three jar packages:

Readers should never forget to import the jquery class library, because I'm using jquery's Ajax to commit the JSON string, like this:

Configuring the JSON Converter

There are two ways to configure a JSON converter, If the note adapter Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter is configured, you need to configure the JSON converter in the adapter as follows:

 <!--used to convert an object to JSON--<bean id= "Stringconverter" class  = "          Org.springframework.http.converter.StringHttpMessageConverter "> <property name=" Supportedmediatypes "> <list> <value>text/plain;charset=UTF-8</value> </list> </property > </bean> <bean id= "Jsonconverter" class  = " Org.springframework.http.converter.json.MappingJackson2HttpMessageConverter "></bean> <bean class  = " Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter "> <property name=" Messageconverters "> <list> <ref bean=" Stringconverter "/> <ref bean=" Jsonconverter "/> </list> </property> </bean> 

However, if you use <mvc:annotation-driven /> Note-driven, you do not have the above configuration, the default is well-equipped. It is recommended to use this, more convenient.

Testing for JSON interaction

Here, I use jquery's Ajax to commit the JSON string and parse the output JSON results. The procedure of the front desk is as follows:

<button onclick= "Sendjson ()" >json Data interaction Test </button><script type= "Text/javascript" >     function Sendjson () {        $.ajax ({            type:"POST",            URL:"${pagecontext.request.contextpath}/ Item/json_test.action ",            data:' {" id ":" 1 "," name ":" Refrigerator "," Price ":" 1999 "} ',            contentType: "Application/json;charset=utf-8",            success:function (data) {                + ":" + data.name);            }        );    } </script>

Then the content of the front itemlist.jsp page should be transformed into:

Then edit the Itemcontroller class and write the following method in the class:

// JSON data Interaction // @RequestBody: Receive JSON data and convert to Pojo object // @ResponseBody: In response to JSON data, convert the Pojo object to JSON data and respond to the @RequestMapping ("/json_test") @ResponseBody  Public Items jsontest (@RequestBody items items) {    return  items;}

Because the foreground passes the ID, name, and price three attributes, it is received in the background with the items class, and there are three properties in this class. The focus is on the @requestbody annotation, which converts the JSON string from the foreground to the items object, and then returns the object back to the foreground with the @responsebody annotation to convert the Items object to JSON format. So the front desk can be resolved after receiving it. Let's take a look at the results of the test:

The result of the response, NULL represents a null value, the original object is returned here, and only the ID, name, and Price properties.

Springmvc the interaction with the foreground JSON data is summed up so much.

SPRINGMVC Learning (10)--SPRINGMVC JSON data interaction with the foreground

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.