我使用@responseBody编写了一个简单的基于休息的控制器,我期望返回一个JSON。
不知怎的,我无法按预期工作。
当我运行网址"http://localhost:8080/my-webapp/amazon/rips"
..返回错误
HTTP状态406 -JBWEB000126:此请求标识的资源只能根据请求“接受”标题生成具有不可接受特征的响应。 有人可以伸出援助之手。
Mycontroller如下:
@Controller
@RequestMapping("/amazon")
public class JsonController {
@RequestMapping(value="/{name}", method = RequestMethod.GET,produces = "application/json")
public @ResponseBody
Book getShopInJSON(@PathVariable String name) {
Book book = new Book();
book.setName(name);
book.setAvailablity(false);
return book;
}
图书课程如下:
public class Book {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isAvailablity() {
return availablity;
}
public void setAvailablity(boolean availablity) {
this.availablity = availablity;
}
private String name ;
private boolean availablity;
}
displatcher servlet如下:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="com.rips.controller" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>${jackson.version}</version>
</dependency>
答案 0 :(得分:3)
在@CodeChimp的帮助下,我意识到我发送的请求没有正确的接受标头。 我使用了Chromes“Advanced Rest client”并使用key =“accept”和value =“application / json”添加了标题,我能够得到正确的响应。
<强>更新强>
我发现调度程序servlet中没有添加<mvc:annotation-driven />
,它使用@RequestBody / @ ResponseBody配置对HTTP消息转换的支持。一旦我添加了这条信息,就不需要使用任何高级的Rest客户端。