我正在测试Spring rest服务,特别是POST方法。
这是我的控制器的代码片段:
@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;
}
员工类:
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;
}
}
我已将jackson库的依赖性包括在pom.xml中 的pom.xml
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
我正在使用firefox海报插件测试服务。
当我提交请求时,我收到状态: 415不支持的媒体类型。
这是我收到的错误消息:
服务器拒绝了此请求,因为请求实体的格式不受所请求方法所请求资源的支持。
请建议我做错了什么?
答案 0 :(得分: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
答案 1 :(得分:0)
尝试以下
import javax.ws.rs.core.MediaType;
@RequestMapping(value =&#34; / testrequest&#34;,method = RequestMethod.POST,consume = MediaType.APPLICATION_JSON,produce = MediaType.APPLICATION_JSON){
}
注意:确保您的实施正常运行。我还没有测试过jackson-mapper-asl&#39;您可以在实现中包含以下依赖项并对其进行测试。
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>3.0.2.Final</version>
</dependency>