2014-11-25 56 views
0

我正在測試spring rest服務,特別是POST方法。
這裏是我的控制器的代碼片段:數據格式測試Spring Rest服務

@RequestMapping(value = "/testrequest", method = RequestMethod.POST, headers = "Accept=application/json") 
    public @ResponseBody String createEmployee(@RequestBody Employee e){ 
     String value = "id " + e.getId() + "firstName " + e.getFirstName() + "lastname " + e.getLastName(); 
     System.out.println(value); 
     return value; 
    } 


Employee類:在pom.xml中傑克遜庫

public class Employee { 

    private int id; 
    private String firstName; 
    private String lastName; 

    public Employee(int id,String firstName,String lastName){ 
     this.id = id; 
     this.firstName = firstName; 
     this.lastName = lastName; 
    } 

    public Employee() { 
     // TODO Auto-generated constructor stub 
    } 

    public int getId() { 
     return id; 
    } 
    public void setId(int id) { 
     this.id = id; 
    } 
    public String getFirstName() { 
     return firstName; 
    } 
    public void setFirstName(String firstName) { 
     this.firstName = firstName; 
    } 
    public String getLastName() { 
     return lastName; 
    } 
    public void setLastName(String lastName) { 
     this.lastName = lastName; 
    } 
} 

我已經包含依賴以及
POM。 xml

 <dependency> 
      <groupId>org.codehaus.jackson</groupId> 
      <artifactId>jackson-mapper-asl</artifactId> 
      <version>1.9.13</version> 
     </dependency> 

我正在測試使用Firefox插件的服務。 enter image description here

當我提交我的請求時,我得到狀態:415不受支持的媒體類型。
這是我得到的錯誤消息: 服務器拒絕此請求,因爲請求實體的格式不是所請求方法的請求資源支持的格式。

請指出我在做什麼錯了?

回答

0

嘗試

@RequestMapping(value = "/testrequest", method = RequestMethod.POST, consumes = "application/json") 

編輯

也許嘗試加入:

<dependency> 
     <groupId>com.fasterxml.jackson.core</groupId> 
     <artifactId>jackson-core</artifactId> 
     <version>2.4.3</version> 
    </dependency> 
    <dependency> 
     <groupId>com.fasterxml.jackson.core</groupId> 
     <artifactId>jackson-databind</artifactId> 
     <version>2.4.3</version> 
    </dependency> 

到您的pom

+0

嘗試過,但它沒有奏效。 – Rakesh 2014-11-25 16:29:17

0

嘗試以下

import javax.ws.rs.core.MediaType;

@RequestMapping(值= 「/ testrequest」,方法= RequestMethod.POST,消耗= MediaType.APPLICATION_JSON,產生= MediaType.APPLICATION_JSON){

}

注:請確保您的實現作品正常。我還沒有測試過'jackson-mapper-asl'。你可以包含以下依賴項來執行並測試它。

 <dependency> 
      <groupId>org.jboss.resteasy</groupId> 
      <artifactId>resteasy-jackson-provider</artifactId> 
      <version>3.0.2.Final</version> 
     </dependency> 
+0

我想將json轉換爲Java對象,不知道它如何在resteasy中工作,但在春季@RequestBody會照顧。 – Rakesh 2014-11-25 17:46:58