Spring MVC的velocity视图技术

1.Velocity
        Velocity是一种易用的模板语言。Velocity将Java代码从Web 页面中分离出来,使用Web站点从长远看更容易维护,并且提供了一种可行的JavaServer Pages替代解决方案。除了JSP,Velocity可能是用于Web应用的最流行的模板语言之一。很多web系统也都采用Velocity作为视图层技术,Spring对Velocity作为视图模板语言提供了很好的支持。
下面让我们看一下Spring MVC如何与Velocity集成。

2.Spring MVC与Velocity集成

(1)配置Velocity引擎
<bean id="velocityConfigurer"
		class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
		<property name="resourceLoaderPath">
			<value>/WEB-INF/vm/</value>
		</property>
		<property name="velocityProperties">
			<props>
				<prop key="input.encoding">gbk</prop>
				<prop key="output.encoding">gbk</prop>
			</props>
		</property>
 </bean>

        VelocityConfigurer负责在Spring的应用上下文中设置Velocity引擎。这里通过属性resourceLoaderPath告诉Velocity到哪里寻找它的模板。一般的web应用都会将模板放到WEB-INF的某个子目录下面,这样可以保证这些模板不能被直接访问.也可以通过velocityProperties属性来设置其他Velocity的其它配置细节,velocityProperties属性使用一个<props>元素来设置多个属性。在上面的配置片断中,input.encoding与output.encoding是设定vm所用的字符集,否则会出现中文乱码。velocityProperties还有很多,具体可参考velocity 相关文档。

(2)配置Velocity视图解析器
        要使用Velocity模板视图,需要在spring配置文件中配置一个视图解析器。配置如下:
<bean id="viewResolver"
	class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
	<property name="suffix">
		<value>.vm</value>
	</property>
	<property name="contentType" >
	         <value>text/html;charset=gbk</value>
	</property>
</bean>

        VelocityViewResolver和Velocity的关系与 InternalResourceViewResolver和JSP的关系相似。InternalResourceViewResolver使用 prefix属性和suffix属性由视图的逻辑名构造出模板文件的路径。对于velocity仅仅设置suffix属性为“.vm”扩展名就可以了。由于模板目录的路径已经通过VelocityConfigurer的resourceLoaderPath属性配置好了,因此这里不需要设置前缀。

(3)如何在VM页面中取得session的相关信息.
        大家都知道,在vm页面中的信息都可以通过ModelAndView对象的模型Map传递给视图,但Spring MVC的VelocityViewResolver解析器默认在VM中无法取到放在session中的相关信息,如需要显示会话中的属性及信息,可以在配置Velocity视图解析器的时候指定。exposeSessionAttributes设为true时告诉VelocityViewResolver是需要将会话中的属性复制到模型中,这样在vm页面中就可以直接访问到。

<bean id="viewResolver"
	class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
	<property name="suffix">
		<value>.vm</value>
	</property>
	<property name="contentType" >
	         <value>text/html;charset=gbk</value>
	</property>
	
	<property name="exposeSessionAttributes">
		<value>true</value>
	</property>
</bean>

猜你喜欢

转载自kim-miao.iteye.com/blog/1053928
今日推荐