SpringMVC @ResponseBody and @RequestBody use

@ResponseBody usage

effect:

  • AcceptThis annotation is used to properly convert the object returned by the Controller method HttpMessageConverterinto the specified format according to the content of the HTTP Request Header, and then write it into the body data area of ​​the Response object.

When to use:

  • When the returned data is not a page of html tags , but data in some other format (such as json, xml, etc.), use .

Configuration returns JSON and XML data

  • add jacksondependencies
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.1</version>
</dependency>
  • turn on

<mvc:annotation-driven />
  • The java code is

@RequestMapping("/testResponseBody")
    public @ResponseBody
    Person testResponseBody() {
        Person p = new Person();
        p.setName("xiaohong");
        p.setAge(12);
        return p;
    }

 

@XmlRootElement(name = "Person")
public class Person {
    private String name;
    private int age;
    public String getName() { return name;    }
    @XmlElement
    public void setName(String name) { this.name = name;    }
    public int getAge() { return age;    }
    @XmlElement
    public void setAge(int age) { this.age = age;    }
}

 

  • Ajax code
$.ajax({
    url: "testResponseBody",
    type: 'GET',
    headers: {
        Accept: "application/xml",
//        Accept:"application/json",
    },
    success: function(data, textStatus){
        console.log(data);
        alert(data);
    },
    error: function (data, textStatus, errorThrown) {
        console.log(data);
    },
        });

 

  analyze

  • PersonIf there is no XML annotation for the configuration class, then only the JSONdata, whatever it Acceptis,

  • If Personthe xml annotation of the class is configured, then if it Acceptcontains applicatin/xml, it will return the xml data. For example, if it is accessed directly through the browser, the browser is http request header appect字段generally
    Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8, so the XML data is returned. If it is
    changed accept: "application/json", the JSON data can be returned.

Using this annotation or ResponseEntity and other similar classes will cause this field to response headerbe accept-charsetincluded, and this field is useless for the response header. The following method can be turned off

<mvc:annotation-driven>
        <mvc:async-support default-timeout="3000"/>
        <!-- utf-8 encoding-->
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
                <property name="writeAcceptCharset" value="false"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

 

@RequestBody use

effect:

  • content-TypeThe annotation is used to convert the method parameters of the Controller into JAVA classes through the appropriate HttpMessageConverter according to the content of the HTTP Request Header

When to use:

  • POSTOr PUTthe data is in JSON format or XML format, rather than the normal key-value pair format.

how to use

The other code is the same as above, configure the Controller as follows:

@RequestMapping(value = "/testRequestBody", method= RequestMethod.POST)
    @ResponseBody
    public Person testRequestBody(@RequestBody Person p) {
        System.out.println("creating a employee:" + p);
        return p;
    }

 

The Ajax code is as follows:

$.ajax({
    url: "testRequestBody",
    data: '{"name":"Xiaohong","age":12}', //Use double quotes!!
    contentType: "application/json;charset=utf-8", // because the above is JSON data

    type: "POST",
    headers: {
//                Accept: "application/xml",
        Accept: "application/json",
    },
    success: function(data, textStatus){
        console.log(data);
        alert(data);
    },
    error: function (data, textStatus, errorThrown) {
        console.log(data);
    },
});
Author: tenlee
Link: https://www.jianshu.com/p/7097fea8ce3f
Source: Jianshu The
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326158234&siteId=291194637