在Spring mvc中视图解析器组件默认为Jsp,这仅仅是其中一种视图解析器。除了使用Jsp作为视图解析器之外,我们还可以使用Velocity、FreeMarker作为视图解析器,该文章主要针对Spring mvc配置Velocity作为spring mvc的视图解析器,至于配置Freemarker与配置Velocity类似,Volocity的定位和Jsp一样,下面主要介绍如何使用Velocity视图解析器代替Jsp视图解析器。
Maven依赖配置(第一次配置的时候,少配置了一个spring-context-support的jar包,导致一直报错,后来通过定位加入了配置spring-context-support)
<!--Velocity模板引擎--> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency><dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency><dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-tools</artifactId> <version>2.0</version> </dependency>
用Velocity视图解析器代替Jsp解析器(中间经历过中文编码乱码问题,可以通过在xml文件中配置编码或是单独建立文件)
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"> <property name="viewClass"> <value>org.springframework.web.servlet.view.velocity.VelocityView</value> </property> <property name="contentType"><value>text/html;charset=UTF-8</value></property> <property name="suffix"> <value>.vm</value> </property> </bean> <!-- velocity视图解析器配置 --> <bean id="velocityConfigurer" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"> <property name="resourceLoaderPath" value="WEB-INF/" /> <property name="velocityProperties"> <props> <prop key="input.encoding">UTF-8</prop> <prop key="output.encoding">UTF-8</prop> <prop key="contentType">text/html;charset=UTF-8</prop> </props> </property> </bean> <!-- 默认jsp视图解析器 --> <!--<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">--> <!--<property name="prefix" value="/WEB-INF/" />--> <!--<property name="suffix" value=".jsp" />--> <!--<property name="viewClass"--> <!--value="org.springframework.web.servlet.view.InternalResourceView" />--> <!--</bean>-->