"Springmvc Learning 09" SPRINGMVC interacting with the foreground JSON data

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.

1. 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 JSON format, the other is to pass the URL of ordinary key/value string over, for these two ways, in the controller will have a different resolution, But the JSON-formatted data returned in the controller is the same. Here's a detailed analysis of how SPRINGMVC interacts with the foreground for JSON data.

2. Preparation of the Environment 2.1 Loading the JSON jar package

SPRINGMVC3 and SPRINGMVC4 for JSON interaction jar package is different, I use SPRINGMVC4, need to import the following three Jar package ().

2.2 Configuring the JSON converter

There are two ways to configure a JSON converter, If the annotation 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>  <Beanclass=" 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.

3. Testing for JSON interaction 3.1 The foreground transmits JSON-formatted data

We use jquery's Ajax to commit JSON strings and parse the output JSON results. The procedure of the front desk is as follows:

//Request JSON, output is JSON function requestjson(){    varJsondata = {"Name":"mobile","Price":"999"}; $.ajax ({type:' Post 'Url:' ${pagecontext.request.contextpath}/requestjson.action ', ContentType:' Application/json;charset=utf-8 ',//specified as JSON type        //Data format is JSON string, commodity informationDataJSON. Stringify (Jsondata), success: function(data){//Return JSON resultsalert (data.name); }           }); }

Take a look at how the controller operates.

//测试请求的是json串(商品信息),输出json(商品信息)//@RequestBody将请求的商品信息的json串转成itemsCustom对象//@ResponseBody将itemsCustom对象转成json输出@RequestMapping("/requestJson")publicrequestJson(@RequestBody ItemsCustom itemsCustom) {    return//由于@ResponseBody注解,将itemsCustom转成json格式返回}

Because the foreground passes the name and price two attributes, it is used in the background to receive the Itemscustom, and this class also has these two properties. The focus is on the @requestbody annotation, which is the JSON string passed from the foreground to the Itemsacustom object, and then return the object back to the foreground by @responsebody annotations to convert the Itemscustom 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 means NULL, the original object is returned, and only the name and price properties

3.2 The front desk transmits data in key/value format

We also use jquery's Ajax to commit key/value strings, parsing the output JSON results. The procedure of the front desk is as follows:

//request Key/value, output is JSON  function   Responsejson   ()  { $.ajax ({type: ' post ' , Url: ' ${pagecontext.request.contextpath}/responsejson.action ' , //request is key/value there is no need to specify ContentType, because the default is Key/value type  // Data format is key/value, commodity information  data: ' name= phone &price=999 ' , Success:function   {        Span class= "Hljs-comment" >//returns the JSON result  alert (data.name); }           }); }

Since the Key/value string is not in JSON format, the controller does not need @requestbody annotations when receiving it, but the JSON-formatted data returned to the foreground needs to be @responsebody annotated, as follows:

//测试请求的是key/value(商品信息),输出json(商品信息)//@ResponseBody将itemsCustom对象转成json输出@RequestMapping("/responseJson")publicresponseJson(ItemsCustom itemsCustom) {    return//由于@ResponseBody注解,将itemsCustom转成json格式返回}

The test results are as follows:

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

Related reading: http://blog.csdn.net/column/details/spring-mvc.html
Learning Note Source: Https://github.com/eson15/SpringMVC_Study

-Willing to share and progress together!
--My Blog home: http://blog.csdn.net/eson_15

Springmvc Learning 09 Springmvc interacting with the foreground JSON data

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.