日期:2014-05-16  浏览次数:20301 次

Spring mvc3.0 rest风格 Spring mvc 配合velocity并使用JSON(三)

之前 一篇文章 讲 Spring mvc3.0 rest风格 Spring mvc 配合velocity (二)

现在讲我在接触spring mvc+velocity+json并且是restful风格,碰到的一些问题

主要就是一个请求路径的问题,rest风格带来了不少的麻烦

本来我们如果使用简单的*.do请求方式,很容易就能实现 json

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver" p:order="1">????????

<property name="mediaTypes">             
<map>                 
<entry key="json" value="application/json"/>             
</map>         </property>       
  <property name="defaultViews">           
  <list>                 
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />            
 </list>         </property>     </bean>

?上面是普通的json数据返回,只要我们以*.json的形式来请求即可得到json数据

但是当我们使用了velocity,并且是rest风格的时候就非常的麻烦了,我之前一直纠结于这个问题,因为我的rest请求形式,所以我没有必要带上.json格式(我这里json并不仅仅用于ajax,比如非ajax请求,ajax完全可以使用*.json的形式)

没办法,在网上搜索一段时间找到了个解决办法

?

采用MappingJacksonHttpMessageConverter 类解决

首先需要修改 spring 的 AnnotationMethodHandlerAdapter

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
	 	<property name="messageConverters">       
             <list>
                 <ref bean="mappingJacksonHttpMessageConverter" />       
             </list>       
         </property>  
	 </bean> 

?

<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" ></bean>  

?

虽然我没有看他的具体源码,我猜测(仅仅是猜测,各位大侠可以拍板)顾名思义mappingJacksonHttpMessageConverter

应该将http response转换为了json数据类型返回给客户端

这样配置之后 ContentNegotiatingViewResolver 就无需配置

直接配置viewResolver 是velocity即可

?

?

?

刚刚看了一下spring官网 ,有另外一种方法可以达到restful的效果,用起来还比较简单,也无需配置

?the @Controller mechanism also allows you to create RESTful Web sites and applications, through the @PathVariable annotation and other features.