SpringMVC中添加Velocity的配置

1、maven配置

除了spring相关配置之外,添加velocity包

<!-- velocity -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-tools</artifactId>
            <version>2.0</version>
        </dependency>
2、修改springMVC配置

<!-- velocity解析器,替换掉原来的jsp -->
 <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
  <property name="contentType" value="text/html;charset=UTF-8" />
  <property name="suffix" value=".vm" />
 </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="input.encoding">UTF-8</prop>
            <prop key="output.encoding">UTF-8</prop>
<prop key="contentType">text/html;charset=UTF-8</prop>
            <prop key="velocimacro.library">macro/macros.vm</prop>
          </props>
        </property>
    </bean>
3、在WEB-INF的子目录下添加模版文件,如 velocity/macro/macros.vm,内容可以放空

4、新建文件WEB-INF/velocity/page1.vm,随便写上HTML代码

5、添加测试文件DemoController

package com.my2.controller;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class DemoController {
 @RequestMapping(value = "/index")
 public ModelAndView toPage1() {
  return new ModelAndView("page1");
 }
}




你可能感兴趣的:(spring,mvc,velocity)