SpringMVC - JSON data exchange

Json (JavaScript Object Notation) , which is a lightweight data interchange format, the format is simple, easy to read, especially currently used widely.

Two methods of interactive mode

① request json, json output, the request is required json string, so the content is required in the front page request is converted into json, not convenient.
② requested key / value, output json. This method is commonly used.

@RequestBody 与 @ResponseBody

@RequestBody : receiving a user to turn the incoming string json pojo

Http request for reading the content (character string), HttpMessageConverter Springmvc interfaces provided to read the content (JSON data) is converted into a Java object bound to the parameter controller and method.

Traditional request parameters:

save? item_id = 001 & item_name = glory of the King & item_type = MOBA & item_price = 0.0

Now request parameters: using the POST request, the request data added json inside body

{
  "item_id" : "001",
  "item_name" : "王者荣耀",
  "item_type" : "MOBA",
  "item_price" : 0.0
}

@ResponseBody : pojo converted into the string in response to user json

A method for the controller object returned by springmvc provided HttPMessageConverter interface into the specified data format, such as: json, xml, etc., through the Response to the client in response.

Environment Configuration

For Gson jackson and two json process dependent, can be added directly.
In addition, other json parser as fastjson need to manually configure HttpMessageConverter.
Indeed, in the SpringMVC, the object is to provide a conversion by JSON string of a class named HttpMessageConverter.
And it provides a default SpringMVC Gson and Jackson's HttpMessageConverter, respectively org.springframework.http.converter.json.GsonHttpMessageConverter and MappingJackson2HttpMessageConverter.
For other JSON parser, developers only need to manually configure the look HttpMessageConverter.

1, jar pack preparation - process of the present embodiment using jackjson

Springmvc default data converted to json MappingJacksonHttpMessageConverter, jackson packages need to be added, as follows:

2, springmvc.xml file configurationrecommended annotation-driven

① If the configuration file is annotations to drive <mvc: annotation-driven />, you do not need any redundant configuration

② If no annotation-driven configuration, you need the following configuration (not recommended in this way)

<!-- 注解适配器 -->
<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> 

 Additional description

By default, HttpMessageConverter JSON org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter processed in the class, or if there is dependent gson jackson in the current project classpath, it will be automatically loaded class, and then create the appropriate HttpMessageConverter.

For fastjson, since the system does not provide automatic support, the developer is required to manually configure the fastjson HttpMessageConverter types , arranged as follows:

① introduced fastjson dependent: fastjson.jar

② joining configuration

< MVC: Annotation-Driven > 
    <-! Not use the default message converter -> 
    < : MVC-Converters Message Register-Defaults = "to true" > 
        <! - Configuration fastjson Support -> 
        < the bean class = "COM .alibaba.fastjson.support.spring.FastJsonHttpMessageConverter " > 
            < Property name =" supportedMediaTypes " > 
                < List > 
                    <-! sequence remains so, to avoid download IE error -> 
                    < value > text / HTML; charset = UTF-. 8 </ value > 
                    <value>application/json</value>
                </list>
            </property>
            <property name="features">
                <list>
                    <value>WriteMapNullValue</value>
                    <value>QuoteFieldNames</value>
                </list>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

HttpMessageConverter assume two things :

① the request result into json
② the json browser sent into objects

JSON request, response achieved JSON

Request :

Receiving a JSON-formatted data, we need to help frame automatically translate into relevant Java objects.
Data submitted by the client to submit JSON data by way of AJAX POST
You need to add the parameter in @RequestBody
@RequestBody: The request is transferred over the JSON data into objects; expect to receive data transmitted to the front end of the rear end of the string json.

Response :

In response to the client is a JSON data item corresponding to the object,
Add @ResponseBody notes in the processing method

In springmvc, the direct receiving json parameter, if the date parameter, then
no need to define the date type converter, the conversion date is provided by gson / jackson / fastjson.

Using JSON data exchange

Front-end code:

note:
① json only in the request body, and therefore, only on JSON post or put request,
② Do not use get / delete request to test the json argument.
function jsonData() {
    $.ajax({
        // request mode 
        type: "POST" ,
         // URL address of the request 
        URL: "$ {} /jsonData.do pageContext.request.contextPath" ,
         // data format transmitted 
        contentType: "file application / JSON" ,
         // transmission data used to convert the object to a string JSON.stringify 
        data: JSON.stringify ({
             "item_id": "007" ,
             "ITEM_NAME": "king glory" ,
             "ITEM_TYPE": "MOBA" ,
             "ITEM_PRICE": 0.0
        }),
        // Callback format 
        dataType: 'JSON' ,
         // callback 
        Success: function (Data) {
            alert(data);
            alert(data.item_name);
        },
        error : function(xhr, ajaxOptions, thrownError) {
            Alert ( "Request Error!" + Item);
             return  to false ;
        }
    });
}

Controller Code:

@ResponseBody
@RequestMapping(value = "jsonData.do")
public ItemInfo jsonData(@RequestBody ItemInfo item) {
    System.out.println("jsonData = " + item);
    return item;
}

Test Results:

 - Data sent by the browser

 - Background reception

 - 浏览器响应:返回一个json字符串

 - alert弹窗

 

Guess you like

Origin www.cnblogs.com/Dm920/p/12148412.html