Velocity是什么?
Velocity是一種基于java的模板引擎技術(shù),有點(diǎn)類似與JSP,它允許頁面設(shè)計(jì)者引用Java中定義的方法。前端頁面設(shè)計(jì)者和后端Java開發(fā)者能夠同時(shí)使用MVC的模式開發(fā)網(wǎng)站,這樣前端能夠把精力放在頁面的設(shè)計(jì)上,后端也可以把精力放在代碼開發(fā)上。Velocity把Java代碼從Web頁面中分離, 使網(wǎng)站可維護(hù)性更強(qiáng).
項(xiàng)目中如何引入, 從一個(gè)簡單demo開始
maven添加如下依賴
<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>
配置spring的視圖解析配置 -- Velocity視圖解析器, 最簡單的配置
Spring的配置文件在哪?
在項(xiàng)目web.xml
中的<servlet>
配置中, 找到DispatcherServlet
的配置,
看contextConfigLocation
的屬性的value
.
<!-- 一.配置試圖解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<!-- 1.前綴, 后綴 , 后綴是決定你模板的后綴的, 可以是其他例如.vm, 如果你喜歡的話 -- >
<property name="prefix" value=""/>
<property name="suffix" value=".html"/>
<!-- 2.為解決頁面亂碼問題, 必須配置 -->
<property name="contentType" value="text/html;charset=utf-8"/>
<!-- 3.toolbox配置文件路徑, 非必須-->
<property name="toolboxConfigLocation" value="/WEB-INF/toolbox.xml"/>
</bean>
<!-- 二.配置velocity模板路徑, 配置文件路徑等 -->
<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<!-- 1.模板位置路徑 -->
<property name="resourceLoaderPath" value="/WEB-INF/velocity/templates"/>
<!-- 2.配置文件路徑 -->
<property name="configLocation" value="classpath:velocity/velocity.properties"/>
</bean>
關(guān)于toolboxConfigLocation
這個(gè)toolbox.xml 配置文件 就是配置java后臺(tái)寫的工具類, 拿到頁面上直接用.類似于jsp技術(shù)中的include某個(gè)工具類的用法.
<?xml version="1.0" encoding="UTF-8" ?>
<toolbox>
<tool>
<key>StringUtil</key>
<class>com.xxx.util.StringUtil</class>
<scope>application</scope>
</tool>
</toolbox>
配置velocity.properties 最簡單的配置
其實(shí)最簡單的配置就是把編碼設(shè)置上. 此處不配置編碼, 頁面會(huì)亂碼. 同時(shí)如果少了上面的
contentType
配置, 同樣亂碼
input.encoding =UTF-8
output.encoding = UTF-8
HelloVelocity的模板文件
在上述的配置文件中
resourceLoaderPath
的路徑下建立模板文件
<!DOCTYPE html>
<html>
<title>Hello Velocity模板文件</title>
<body>
<h1>Hello $name !</h1>
<h2>當(dāng)前時(shí)間 : $date !</h2>
</body>
</html>
$name
和$date
是velocity的語法, 類似于el 的${name}
${date}
, 所以下一步上后臺(tái)給這兩個(gè)key賦值
后臺(tái)Controller代碼
@Controller
@RequestMapping("/velocity")
public class VelocityController {
@RequestMapping(value="/test")
public String test(Model model) {
String name = "安仔";
model.addAttribute("name", name);
model.addAttribute("date", new Date());
return "velocity";
}
}
最終頁面呈現(xiàn)類似于jsp, 但效率高于jsp
模板頁面