0
点赞
收藏
分享

微信扫一扫

Spring整合velocity


版本要1.4 , 1.6版本出现问题:Failed to load Directive: org.apache.velocity.tools.generic.directive.Ifnull, 不知道怎么解决.


[url]http://yixiandave.iteye.com/blog/1880371[/url]
五、velocity和spring mvc的整合
本篇资料五花八门,但是大多是spring2.5的资料了
配置文件不用多说,首先是velocity的配置信息

<bean id="velocityConfigurer" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">  
<property name="resourceLoaderPath" value="WEB-INF/velocity"/>
<property name="velocityProperties">
<props>
<prop key="input.encoding">utf-8</prop>
<prop key="output.encoding">utf-8</prop>
</props>
</property>
</bean>


设定细节


<bean id="velocityConfigurer" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"> 
<property name="resourceLoaderPath">
<value>WEB-INF/velocity/</value>
</property>
<property name="velocityProperties">
<props>
<prop key="directive.foreach.counter.name">loopCounter</prop>
<prop key="directive.foreach.counter.initial.value">0</prop>
</props>
</property>
</bean>



然后引入ViewResolver


<bean id="velocityViewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">  
<property name="suffix" value=".vm"/>
<property name="contentType" value="text/html;charset=utf-8"/>
</bean>




要补充的是Spring3 MVC中的Controller大多都是普通类了,我也不喜欢在一个映射方法中添加一堆莫名其妙的参数


实际上Spring支持直接的字符串解析:


@Controller  
@RequestMapping("/")
public class IndexController {
@RequestMapping("/index.htm")
public String showIndex(){
return "index";
}
}



这里index会直接映射到WEB-INF/velocity/index.vm文件。


注意return字符串中不需要添加.vm字符串



###################补充2013-06-02#######################


也可以直接将配置信息写入properties文件


在VelocityConfigurer类的bean中添加


<property name="configLocation" value="classpath:velocity.properties"/>



#########################################################


-----------------------------------------------------------


六、velocity和javamail的整合


javamail可以使用velocity作为模板来发送模板邮件


具体在这里已经很清楚了:http://gundumw100.iteye.com/blog/515346


博主在这里要补充的是里面引用的是org.springframework.ui.velocity.VelocityEngineFactoryBean来创建一个VelocityEngine对象。


但是velocity和spring mvc的整合则使用了org.springframework.web.servlet.view.velocity.VelocityConfigurer


我们没必要为了javamail还单独配置一个VelocityEngine方法。


通过阅读源码发现org.springframework.web.servlet.view.velocity.VelocityConfigurer实际有一个getVelocityEngine()方法。


因此我们可以直接把Confirgurer注入到javamail发送类


private VelocityEngine velocityEngine;  
@Resource(name = "velocityConfigurer")
private void setVelocityConfigurer(VelocityConfigurer velocityConfigurer){
velocityEngine = velocityConfigurer.getVelocityEngine();
}



这个和前面的方法是等效的


举报

相关推荐

0 条评论