RESTful服务中很重要的一个特性便是同一资源,多种表述.也即以下面描述的三种方式: html
GET /user/123 HTTP/1.1 Accept: application/xml //将返回xml格式数据 GET /user/123 HTTP/1.1 Accept: application/json //将返回json格式数据
/user/123.xml 将返回xml格式数据 /user/123.json 将返回json格式数据 /user/123.html 将返回html格式数据
3.使用参数 java
/user/123?format=xml //将返回xml数据 /user/123?format=json //将返回json数据
下面是ContentNegotiatingViewResolver的彻底配置. 程序员
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <!-- 设置为true以忽略对Accept Header的支持 --> <property name="ignoreAcceptHeader" value="true" /> <!-- 在没有扩展名时即: "/user/1" 时的默认展示形式 --> <property name="defaultContentType" value="text/html" /> <!-- 扩展名至mimeType的映射,即 /user.json => application/json --> <property name="mediaTypes"> <map> <entry key="json" value="application/json" /> <entry key="xml" value="application/xml" /> </map> </property> <!-- 用于开启 /userinfo/123?format=json 的支持 --> <property name="favorParameter" value="false" /> <property name="viewResolvers"> <list> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/pages" /> <property name="suffix" value=".jsp"></property> </bean> </list> </property> <property name="defaultViews"> <list> <!-- for application/json --> <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" /> <!-- for application/xml --> <!-- <bean class="org.springframework.web.servlet.view.xml.MarshallingView" > <property name="marshaller"> <bean class="org.springframework.oxm.xstream.XStreamMarshaller"/> </property> </bean> --> </list> </property> </bean>