Spring MVC @ResponseBody和@RequestBody使用


@ResponseBody用法:

作用:該注解用於將Controller的方法返回的對象,根據HTTP Request Header的Accept的內容,通過適當的HttpMessageConverter轉換為指定格式后,寫入到Response對象的body數據區。

使用時機:

返回的數據不是html標簽的頁面,而是其他某種格式的數據時(如json,xml等)使用。

配置返回json和xml數據

添加jackson依賴

<dependence>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-core</artifactId>
     <version>2.8.1</version>
</dependence>
<dependence>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifacted>jackson-databind</srtifacted>
      <version>2.8.1</version>
</dependence>

開啟<mvc:annotation-driven>

java代碼:

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

Person類:

@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;
    }
    public void setAge(int age) {
        this.age = age;
    }
}    

Ajax代碼:

$.ajax({
    url:"testResponseBody",
    type:'Get',
    header: {
         Accept:"application/xml" ,  
    },
    success:function(data,testStatus){
        console.log(data);
        alert(data)
    },
    error:function(data,textStatus,errorThrown) {
        console.log(data);
    }
});

分析:

如果沒有配置Person類的xml注解,那么只會json數據,無論Accept是什么。

如果配置了Person類的xml注解,那么如果Accept含有application/xml,就會返回xml數據,例如通過瀏覽器直接訪問,瀏覽器的http request header appect字段一般都為Accept:text/html application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8,故返回XML數據。

改accept:“application/json”,即可返回json數據

用此注解或者ResponseEntity等類似類,會導致response header 含有accept-charset這個字段,而這個字段對於響應頭是沒有用的,以下方法可以關掉。

<mvc:annotation-driven>
    <mvc:async-support default-timeout="3000/">
    <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使用:

作用:注解用於將controller的方法參數,根據HTTP Request Header的content-Type的內容,通過適當的HttpMessageConverter轉換為java類

使用時機:

POST或者PUT的數據是JSON格式或者是JSON格式或者是XML格式,而不是普通的鍵值對形式

如何使用:

配置controller

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

Ajax代碼如下:

$.ajax({
    url:"testResponseBody",
    data:{"name":"小紅","age":"123"}, // json形式要用雙引號
    content
});

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM