還是在springmvc工程上進行整合
- 添加jar包
右鍵pom.xml,菜單maven-->Add Dependency ,可以搜尋添加velocity和velocity-tools兩個包,另外還需要添加spring-context-support,不然會報錯
- 添加vm檔案
在WEB-INF下建立了一個views檔案夾,裡面加了兩個檔案,一個用來做模闆,一個具體頁面。
layout.vm
<head>
<title>Spring MVC and Velocity</title>
</head>
<body>
<h1>Spring MVC and Velocity</h1>
$screen_content
<hr />
Copyright © 2016 lkf
</body>
</html>
hello.vm
welcome ${user}
- 配置
在servlet的配置檔案中,加入velocity的相關配置,注意路徑
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.lucky.study"/>
<bean id="velocityConfig"
class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/WEB-INF/views/" />
<property name="velocityProperties">
<props>
<prop key="input.encoding">UTF-8</prop>
<prop key="output.encoding">UTF-8</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
<property name="cache" value="true" />
<property name="prefix" value="" />
<property name="layoutUrl" value="layout.vm" />
<property name="suffix" value=".vm" />
<property name="contentType"><value>text/html;charset=UTF-8</value></property>
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
- java檔案
package com.lucky.study.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class MyController {
@RequestMapping(value = "/hello")
public ModelAndView hello() {
ModelAndView mv = new ModelAndView();
mv.addObject("user", "lucky");
//設定邏輯視圖名,視圖解析器會根據該名字解析到具體的視圖頁面
mv.setViewName("hello");
return mv;
}
}
運作後 通路http://localhost:8080/velocity/hello.do