如果我们使用Spring MVC开发REST,它将支持XML和JSON数据。我在Spring配置豆app-servlet.xml
Spring REST 3支持XML和JSON
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"
p:order="1">
<property name="mediaTypes">
<map>
<entry key="xml" value="application/xml" />
<entry key="json" value="application/json" />
</map>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<property name="marshaller">
<bean class="org.springframework.oxm.xstream.XStreamMarshaller"
p:autodetectAnnotations="true" />
</property>
</bean>
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
</list>
</property>
</bean>
我的春天REST控制器写道ContentNegotiationViewResorver是:
@Controller
@RequestMapping("/rest/customers")
class CustomerRestController {
protected Log log = LogFactory.getLog(CustomerRestController.class);
@RequestMapping(method = POST)
@ResponseStatus(CREATED)
public void createCustomer(@RequestBody Customer customer,
HttpServletResponse response) {
log.info(">>>" + customer.getName());
response.setHeader("Location", String.format("/rest/customers/%s",
customer.getNumber()));
}
@RequestMapping(value = "/{id}", method = GET)
@ResponseBody
public Customer showCustomer(@PathVariable String id) {
Customer c = new Customer("0001", "teddy", "bean");
return c;
}
@RequestMapping(value = "/{id}", method = PUT)
@ResponseStatus(OK)
public void updateCustomer(@RequestBody Customer customer) {
log.info("customer: " + customer.getName());
}
我设置@XStreamAlias("customer")
标注在我的客户领域类。 但是,当我尝试访问http://localhost:8080/rest/customers/teddy.xml
它总是响应JSON数据。
我在我的客户域类中设置了@XmlRootElement(name="customer")
注释。 但是,当我尝试访问http://localhost:8080/rest/customers/teddy.json
它总是响应XML数据。
有什么不对吗?
凡在控制器应用程序/客户/ teddy.xml映射? – chris
对不起..网址是:/rest/customers/teddy.xml,这个网址应该调用showCustomer方法。而泰迪是{id}参数。 –
你如何访问该URL?网页浏览器?您是否在请求中发送适当的内容类型编码标头? – skaffman