如果我們使用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