2014-11-25 91 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