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

本文探讨了在SpringMVC结合Velocity模板引擎时遇到的RESTful风格JSON数据返回问题及解决方案,包括如何通过MappingJacksonHttpMessageConverter进行HTTP响应转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前 一篇文章 讲 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值