我需要创建一个可以生成XML或JSON的API。例如如果请求的路径是
/getData吗?format = XML
应该生成XML,如果请求的路径是
/getData吗?JSON格式=
应该生成JSON。
我已经学习了Spring教程"构建RESTful web服务"所以我只是想把这些代码修改一下,这样它就能生成XML和JSON了。
我应该采取哪些步骤?
第一步:确保在JSON和XML呈现的类路径上分别有Jackson 2和Castor。如果使用Maven,这些可以作为依赖项添加。您还可以对JSON使用GSON,对XML使用JAXB。
步骤2:从控制器方法返回一个Java对象,类似于:
@RequestMapping("/users")
public @ResponseBody Users all()
{
return ServiceLocator.findUserService().all();
}
步骤3:在Spring应用程序上下文文件中配置JSON和XML转换器,如下所示:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="prettyPrint" value="true" />
<property name="supportedMediaTypes" value="application/json" />
</bean>
<bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<constructor-arg>
<bean class="org.springframework.oxm.castor.CastorMarshaller" />
</constructor-arg>
<property name="supportedMediaTypes" value="application/xml" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
步骤4:在Spring应用程序上下文文件中配置ContentNegotiatingViewResolver
,如下所示:
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
</bean>
一旦完成这些步骤,就可以通过多种方式获得不同的表示:
XML>-
http://server/users.xml
-
http://server/users?format=xml
-
http://server/users
, HTTP头Accepts
设置为application/xml
-
http://server/users.json
-
http://server/users?format=json
-
http://server/users
, HTTP头Accepts
设置为application/json