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>