restful服务中有一个很重要的准则就是
同一资源,多种表述
即,当我们需要到rest服务器上去拉去资源的时候,
同一份资源,若客户端期望得到json,rest服务器则将资源以json的形式返回,若是html文档,则服务器将数据渲染成html,在返回。
如下面描述的三种方式:
方式1 使用扩展名
http://www.helloworld.com/user.xml 呈现xml文件
http://www.helloworld.com/user.json 呈现json格式
http://www.test.com/user 使用默认view呈现,比如jsp等
方式2 使用http request header的Accept
GET /user HTTP/1.1
Accept:application/xml
GET /user HTTP/1.1
Accept:application/json
….
方式3 使用参数
http://www.helloworld.com/user?format=xml
http://www.helloworld.com/user?format=json
好了既然说要在Springmvc中实践这一原则。
那么就进入正题如何实现的吧。
Spring中有一个类
org.springframework.web.servlet.view.ContentNegotiatingViewResolver
这个类里面可以配置一些策略。
根据不同的情况使用不同的视图渲染引擎。
<!--通过此类我们可以实践Restful的一个资源多种表现形式的原则-->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="favorParameter" value="false" />
<property name="ignoreAcceptHeader" value="false" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
<!--默认的视图-->
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"></bean>
</list>
</property>
</bean>
<!--如果在ContentNegotiatingViewResolver类中没有找到相对应的视图,则使用jsp的视图-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="2" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
</bean>
根据url的结尾是否以.json结尾来判断是返回json数据还是html文档。
@RequestMapping("/user/{presentationType}")
public Object user(@PathVariable String presentationType, Model model) {
User u = new User();
model.addAttribute("User", u);
return "User";
}