SPRINGMVC Study Notes (-json) data interaction

Source: Internet
Author: User

SPRINGMVC Study Notes (-json) data interaction

Tags: springmvc

    • SPRINGMVC Learning notes 18-json data interaction
      • SPRINGMVC for JSON interaction
      • Environment preparation
        • Adding dependencies for JSON transformations
        • Configuring the JSON Converter
      • JSON Interactive test
        • Input JSON string output is JSON string
        • Input keyvalue output is JSON string

This article mainly describes how to interact with JSON data in SPRINGMVC. First environment preparation and configuration, and then show "input JSON string, output is JSON string" and "input key/value, output is JSON string" Two cases of interaction

SPRINGMVC for JSON interaction

JSON data formats are used more frequently in interface calls and in HTML pages. The JSON format is simpler and more convenient to parse.

Analogy: WebService interface. Transmits JSON data.

    • Request JSON, output JSON, request is the JSON string, so in front-end pages need to convert the contents of the request to JSON, not very convenient.
    • Request Key/value, output JSON. This method is more often used.
Environment ready to join JSON conversion dependency

At the beginning I was less jackson-databind dependent, the program various error.

<!--JSON conversion --<dependency>    <groupId>Com.fasterxml.jackson.core</groupId>    <artifactid>Jackson-databind</artifactid>    <version>2.7.2</version></Dependency><dependency>    <groupId>Org.codehaus.jackson</groupId>    <artifactid>Jackson-mapper-asl</artifactid>    <version>1.9.13</version></Dependency>

Viewing a dependency tree

[INFO] +-com. Fasterxml. Jackson. Core: Jackson-databind:jar:2.7. 2: Compile[info] | +-com. Fasterxml. Jackson. Core: Jackson-annotations:jar:2.7. 0: Compile[info] | \-com. Fasterxml. Jackson. Core: Jackson-core:jar:2.7. 2: compile[info] \-org. Codehaus. Jackson: Jackson-mapper-asl:jar:1.9.: compile[info] \-org. Codehaus. Jackson: Jackson-core-asl:jar:1.9.: Compile
Configuring the JSON Converter

Adding in the annotation adaptermessageConverters

<!--Note 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>

Note: It is assumed that the <mvc:annotation-driven /> above content is not defined.

JSON Interactive test

Show two buttons to test separately

    • JSP page
<%--Created by IntelliJ idea. User:brian Date: 3/7time: £ º   To change this template use File | Settings | File templates.--%>    <%@ page contenttype="Text/html;charset=utf-8" language="java" %><html><head>    <meta http-equiv="Content-type" Content="text/html; Charset=utf-8 ">    <title>JSON Interactive test</title>    <script type="text/javascript" src="${ PageContext.request.contextPath}/js/jquery-1.4.4.min.js "></script>    <script type="Text/javascript"> //Request JSON, output is JSONfunction requestjson(){ omitted} //Request Key/va Lue Output is JSONfunction responsejson(){ omitted}                        </script></head><body><input type="button" onclick="Requestjson ()" value= "Request json. The output is JSON "/><input type="button" onclick="Responsejson ()"  Value="Request Key/value, Output is json"/></body>
    • Controller
@Controllerpublicclass JsonTest {    省略}
    • Test results
Input JSON string, output is JSON string

Use jquery's AJAX submission JSON string to parse the output JSON results.

    • JSP page
//request JSON, output is JSON  function   Requestjson   ()  { $.ajax ({type: ' post ' , Url: ' ${pagecontext.request.contextpath}/requestjson.action ' , ContentT Ype: ' application/json;charset=utf-8 ' , //data format is a JSON string, Product information  data: ' {" name phone ", " price": 999} ' , Success:function   {//return json  result  alert (data); }    });}
    • Controller
//请求json串(商品信息),输出json(商品信息)//@RequestBody将请求的商品信息的json串转成itemsCustom对象//@ResponseBody将itemsCustom转成json输出@RequestMapping("/requestJson")publicrequestJson(@RequestBody ItemsCustom itemsCustom){    //@ResponseBody将itemsCustom转成json输出    return itemsCustom;}
    • Test results

Can see that the HTTP header of request and response is Content-typeapplication/json;charset=utf-8

Input key/value, output is JSON string

Using jquery's Ajax to commit key/value strings, parsing the output JSON results

    • jsp page
//request Key/value, The 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 the Key/value type  // ContentType: ' Application/json;charset=utf-8 ',  //data format is a JSON string. Product information  data: ' name= phone &price=999 ' , Success:function   {        //returns the JSON result  alert (data.name); }    });}
    • Controller
//请求key/value,输出json@RequestMapping("/responseJson")publicresponseJson(ItemsCustom itemsCustom){    //@ResponseBody将itemsCustom转成json输出    return itemsCustom;}
    • Test results

Can see. The default content-type for Key/value key-value pairs is, at the application/x-www-form-urlencoded same time. We received a response to "phone"

Author @brianway Many other articles: personal site | CSDN | Oschina

SPRINGMVC Study Notes (-json) data interaction

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.