非框架類總綱
友情鏈接:Velocity-前傳
http://m.itdecent.cn/p/b977f3f4e3d6
官方文檔
http://velocity.apache.org/tools/3.1/apidocs/index.html
一、velocity tools 介紹
Velocity Tools 是 Velocity模板引擎的一個子項目,用于將 Velocity 與 Web開發(fā)環(huán)境集成的工具包。
VelocityTools項目分為兩個部分:GenericTools和VelocityView .
- GenericTools :
GenericTools是一組類,它們提供在標(biāo)準(zhǔn)Velocity項目中使用工具的基本基礎(chǔ)結(jié)構(gòu),以及在通用Velocity模板中使用的一組工具。例如 : DateTool、NumberTool和RenderTool很多其他可用的工具 - Velocity view : 包括所有的通用工具結(jié)構(gòu)和在web應(yīng)用程序的視圖層中使用Velocity的專用工具。這包括用于處理Velocity模板請求的
VelocityViewServlet或VelocityLayoutServlet、用于在JSP中嵌入Velocity的VelocityViewTag和用于在Velocity模板中嵌入JSP標(biāo)記庫的Maven插件。這里流行的工具是LinkTool和ParameterTool。
二、GenericTools使用
1、GenericTools介紹
GenericTools : GenericTools是一組類,它們提供在標(biāo)準(zhǔn)Velocity項目中使用工具的基本基礎(chǔ)結(jié)構(gòu),以及在通用Velocity模板中使用的一組工具。
簡單來說, GenericTools就是Velocity官方提供的一組可以在模板中使用的工具類庫
2、GenericTools環(huán)境搭建
2-1、創(chuàng)建項目
2-2、導(dǎo)入依賴
<dependencies>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.apache.velocity.tools</groupId>
<artifactId>velocity-tools-generic</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>8</source>
<target>8</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
2-3、創(chuàng)建模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
當(dāng)前時間 : $date.get('yyyy-MM-dd HH:mm:ss')
</body>
</html>
2-4、編寫配置

<?xml version="1.0" encoding="UTF-8"?>
<tools>
<toolbox scope="application">
<tool class="org.apache.velocity.tools.generic.DateTool"></tool>
</toolbox>
</tools>
2-5、輸出數(shù)據(jù)
public void test2() throws IOException {
// 創(chuàng)建引擎
VelocityEngine ve = new VelocityEngine();
// 設(shè)置模板加載路徑,這里設(shè)置的是class下
ve.setProperty(Velocity.RESOURCE_LOADER, "class");
ve.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
// 進(jìn)行初始化操作
ve.init();
// 加載toolbox
ToolManager manager = new ToolManager();
manager.configure("configuration.xml");
// 加載模板,設(shè)定模板編碼
Template tpl = ve.getTemplate("vms/01-velocitytools.vm", "UTF-8");
// 設(shè)置初始化數(shù)據(jù)
Context context = manager.createContext();
context.put("now", new Date ());
FileWriter fw = new FileWriter("D:\\work\\demo1.html");
//合并數(shù)據(jù)到模板
tpl.merge(context, fw);
//釋放資源
fw.close();
}
3、工具類及案例
格式化工具類的主要作用就是對數(shù)據(jù)進(jìn)行格式化之后輸出 , 例如 : 日期格式化 , 數(shù)字格式化等 , GenericTools提供的工具類有很多 , 隨著時間的推移很多工具類已經(jīng)過期, 有更好更安全的替代方案, 這里我們僅僅介紹一些常用工具類
1、DateTool
用于訪問和格式化日期以及格式化Date和Calendar對象。該工具還可以用于在各種日期類型之間進(jìn)行轉(zhuǎn)換。
模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
年 : $date.getYear()
月: $date.getMonth()
日: $date.getDay()
當(dāng)前時間 : $date.format($now)
當(dāng)前時間 : $date.format("yyyy-MM-dd HH:mm:ss",$now)
當(dāng)前時間 : $date.get('yyyy-MM-dd HH:mm:ss')
</body>
</html>
配置:
<toolbox scope="application">
<tool key="date" class="org.apache.velocity.tools.generic.DateTool" format="yyyy-MM-dd"></tool>
</toolbox>
2、NumberTool
用于訪問和格式化任意數(shù)值類型對象。該工具還可以用于檢索NumberFormat實例或與各種數(shù)字類型進(jìn)行相互轉(zhuǎn)換。
模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
原始數(shù)據(jù) : $myNumber 12.88
格式化 : $number.format($myNumber) 12.88
取整 : $number.integer($myNumber) 13
</body>
</html>
配置:
<toolbox scope="application">
<tool key="number" class="org.apache.velocity.tools.generic.NumberTool" />
</toolbox>
3、MathTool、
用于在Velocity中執(zhí)行數(shù)學(xué)運算。
模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
num1+num2 : $math.add($num1,$num2);
num1-num2 : $math.sub($num1,$num2);
num1*num2 : $math.mul($num1,$num2);
num1/num2 : $math.div($num1,$num2);
向上取整 : $math.ceil($math.div($num1,$num2))
向下取整 : $math.floor($math.div($num1,$num2))
四舍五入 : $math.roundTo(2,$math.div($num1,$num2)) ## 第一個參數(shù)保留的位數(shù) , 第二個參數(shù)運算的值
</body>
</html>x
配置:
<toolbox scope="application">
<tool key="math" class="org.apache.velocity.tools.generic.MathTool" />
</toolbox>
4、DisplayTool
用于控制數(shù)據(jù)顯示和隱藏 , 以及數(shù)據(jù)格式的處理
模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
## list方法用于展示數(shù)據(jù)或集合中的數(shù)據(jù) , 默認(rèn)的展示格式為 A, B and C
默認(rèn)輸出格式 : $display.list($list)
使用,分割輸出 : $display.list($list,",")
## truncate方法用于字符串截取 , 默認(rèn)截取30個長度
字符串截取, 默認(rèn)30個長度 : $display.truncate("truncate方法用于字符串截取默認(rèn)截取30個長度")
字符串截取, 給定20個長度 : $display.truncate("truncate方法用于字符串截取默認(rèn)截取30個長度",20)
字符串截取, 給定20個長度 : $display.truncate("truncate方法用于字符串截取默認(rèn)截取30個長度",20,"")
## alt方法用于判斷給定的數(shù)據(jù)是否為空 , 如果為空展示第二個參數(shù) , 如果不為空展示數(shù)據(jù)本身
不為空:$display.alt($num1,"num1不為空")
為空:$display.alt($num3,"num3為空")
</body>
</html>
配置:
<toolbox scope="application">
<tool key="display" class="org.apache.velocity.tools.generic.DisplayTool"/>
</toolbox>
5、EscapeTool
用于對一些特殊字符進(jìn)轉(zhuǎn)義處理 , 例如 $ , #, & 等...
模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
$velocity -------轉(zhuǎn)換 -------
$esc.velocity($velocity)
$html -------轉(zhuǎn)換 -------
$esc.html($html)
$url -------轉(zhuǎn)換 -------
$esc.url($url)
$esc.unurl($esc.url($url))
$esc.dollar ## $
$esc.d ## $
$esc.hash ## #
$esc.h ## #
$esc.backslash ## \
$esc.b ## \
$esc.quote ## "
$esc.q ## "
$esc.singleQuote ## '
$esc.s ## '
$esc.exclamation ## !
$esc.e ## !
</body>
</html>
配置:
<toolbox scope="application">
<tool key="esc" class="org.apache.velocity.tools.generic.EscapeTool"/>
</toolbox>
6、FieldTool
用于訪問類中定義public修飾的靜態(tài)常量
6.1、定義MyConstants常量類
public class MyConstants {
public static String COUNTER_NAME = "COUNTER";
}
6.2、定義Counter常量類
public class Counter {
public static Integer MAX_VALUE = 100 ;
public static Integer MIN_VALUE = 100 ;
}
模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
## 訪問在配置中定義的靜態(tài)常量
獲取MyConstants中的常量 : $field.COUNTER_NAME
## 通過一個類中的常量
獲取Counter類中的量 : $field.in("com.kk.counter.Counter").MAX_VALUE
## 傳入一個對象的實例 , 通過對象的實例獲取其類中定義的常量
獲取日歷對象中的YEAR常量 : $field.in($calender).YEAR
## 默認(rèn)情況下, 當(dāng)我們查找了一個類的常量之后, 這個類回保存在FieldTool工具中, 可以直接獲取下一個常量
獲取日歷對象中的DATE常量 : $field.DATE ## 因為之前已經(jīng)獲取過 , 所以可以直接獲取
</body>
</html>
配置:
<toolbox scope="application">
<tool key="field" class="org.apache.velocity.tools.generic.FieldTool" include="com.kk.constants.MyConstants"/>
</toolbox>
include屬性可以引入一些類, 引入之后想要獲取其中的常量, 直接使用 $field.常量字段名稱即可 ! 引入多個類以,分割
7、ClassTool
ClassTool用于訪問一個類的Class對象信息以及其Filed , Method , Constructor等信息 , 它的設(shè)計沒有考慮到代碼的反射執(zhí)行,因此無法通過反射執(zhí)行代碼。
模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
## 獲取要查看的類上的所有注解 , 只有運行時期的注解才能夠獲取到
注解 : $class.getAnnotations()
構(gòu)造方法 :
#foreach($constructor in $class.getConstructors())
$constructor
#end
屬性 :
#foreach($f in $class.getFields())
$f
#end
方法 :
#foreach($m in $class.getMethods())
$m
#end
包名 : $class.getPackage()
類名 : $class.getName()
## 也可以不通過配置文件 , 自己指定一個要查找的類
包名 : $class.inspect("java.lang.String").getPackage()
類名 : $class.inspect("java.lang.String").getName()
構(gòu)造方法 :
#foreach($constructor in $class.inspect("java.lang.String").getConstructors())
$constructor
#end
</body>
</html>
配置:
<toolbox scope="application">
<tool class="org.apache.velocity.tools.generic.ClassTool" inspect="com.kk.utils.Result" ></tool>
</toolbox>
inspect : 指定一個需要查找的類
8、ContextTool
用于獲取Context中保存的數(shù)據(jù)和元數(shù)據(jù)
模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
context中的所有key :
#foreach( $key in $context.keys )
$key
#end
<br>
context中的所有value :
#foreach( $value in $context.values )
$value
#end
<br>
context中的所有key-value :
#foreach( $key in $context.keys )
$key = $context.get($key)
#end
</body>
</html>
配置:
<toolbox scope="request">
<tool key="context" class="org.apache.velocity.tools.generic.ContextTool"/>
</toolbox>
需要注意的是在application作用范圍中沒有ContextTool , 所以scope需要指定為request
9、RenderTool
Render用于將給定的字符串當(dāng)作VTL秩序
模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
#set($list = [1,2,3] )
#set($object = '$list' )
#set($method = 'size()' )
## 將字符串當(dāng)作VTL秩序
$render.eval("${object}.$method")
## 使用當(dāng)前上下文遞歸地評估包含VTL的字符串,并將結(jié)果作為字符串返回。
#macro(say_hi)
hello world!
#end
#set($foo = "#say_hi()")
#set($bar = "$foo" )
$render.recurse($bar)
</body>
</html>
配置:
<toolbox scope="request">
<tool key="render" class="org.apache.velocity.tools.generic.RenderTool"></tool>
</toolbox>
使用recurse遞歸時 ,RenderTool 默認(rèn)將遞歸限制為20個周期,以防止無限循環(huán)
10、SortTool
SortTool用于對集合和數(shù)組數(shù)據(jù)進(jìn)行排序 , 在排序操作期間,通過調(diào)用compareTo() 來進(jìn)行比較,但要調(diào)用compareToIgnoreCase()的字符串除外。將集合數(shù)據(jù)轉(zhuǎn)化為合適的類型后 , 通過調(diào)用Collections.sort()來執(zhí)行排序
模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
簡單類型排序 :
#set($strList = $sorter.sort($strs))
#foreach($str in $strList)
$str
#end
對象類型排序 - 單個字段 :
#set($users = $sorter.sort($userList,"age:asc"))
#foreach($user in $users)
$user.name : $user.age : $user.sex
#end
對象類型排序 - 多字段 :
#set($users = $sorter.sort($userList,["sex:desc","age:asc"]))
#foreach($user in $users)
$user.name : $user.age : $user.sex
#end
</body>
</html>
配置:
<toolbox scope="request">
<tool key="render" class="org.apache.velocity.tools.generic.RenderTool"></tool>
</toolbox>
SortTool已經(jīng)被標(biāo)注為過期, 建議使用下面CollectionTool的排序方法
11、CollectionTool
CollectionTool允許用戶對集合中包含的對象公開的任意任意屬性集對集合(或數(shù)組,迭代器等)進(jìn)行排序,并通過拆分字符串來生成數(shù)組。
模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
簡單類型排序 :
#set($strList = $collection.sort($strs))
#foreach($str in $strList)
$str
#end
對象類型排序 - 單個字段 :
#set($users = $collection.sort($userList,"age:asc"))
#foreach($user in $users)
$user.name : $user.age : $user.sex
#end
對象類型排序 - 多字段 :
#set($users = $collection.sort($userList,["sex:desc","age:asc"]))
#foreach($user in $users)
$user.name : $user.age : $user.sex
#end
拆分字符串 :
#set($str="hello word , how are you !")
#foreach($s in $collection.split($str))
$s
#end
</body>
</html>
配置:
<tool key="collection" class="org.apache.velocity.tools.generic.CollectionTool" stringsDelimiter=" ">
</tool>
stringsDelimiter : 指定進(jìn)行字符串分割時的分割符 , 默認(rèn)是,
12、XmlTool
XmlTool用于讀取和瀏覽XML文件。它底層使用dom4j為遍歷XML文件提供完整的XPath支持。
xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user id="1" name="楊過" sex="男" age="18" > 喜歡看書 </user>
<user id="2" name="小龍女" sex="男" age="18" > 喜歡睡覺 </user>
<user id="3" name="郭靖" sex="男" age="18" > 喜歡玩游戲 </user>
<user id="4" name="黃蓉" sex="男" age="18" > 喜歡喝酒 </user>
</users>
模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
$xml.find("http://user[@id='1']")
$xml.find("http://user[@id='1']").attr("name")
$xml.find("http://user[@id='1']").text
</body>
</html>
配置:
<toolbox scope="application">
<tool key="xml" class="org.apache.velocity.tools.generic.XmlTool" resource="xml/user.xml"/>
</toolbox>
resource : 加載類路徑下的XML資源
source : 加載一個URL路徑下的XML資源
三、Velocity View
1、Velocity View j介紹
VelocityView包含所有GenericTools并添加了用于在Web應(yīng)用程序(Java EE項目)的視圖層中使用Velocity的基礎(chǔ)結(jié)構(gòu)和專用工具。這包括用于處理Velocity模板請求的VelocityViewServlet或VelocityLayoutServlet,以及用于將Velocity嵌入JSP中的VelocityViewTag。
2、環(huán)境搭建
2-1、導(dǎo)入依賴(插件:鎖定 JDK版本,Tomcat版本)
<dependencies>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.apache.velocity.tools</groupId>
<artifactId>velocity-tools-generic</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>org.apache.velocity.tools</groupId>
<artifactId>velocity-tools-view</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-api</artifactId>
<version>9.0.10</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>11</source>
<target>11</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<port>8080</port>
<uriEncoding>utf-8</uriEncoding>
</configuration>
</plugin>
</plugins>
</build>
2-2、配置Servlet
在web.xml中配置整合VelocityViewServlet
<?xml version="1.0" encoding="UTF-8"?>
<web-app
version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>velocity</servlet-name>
<servlet-class>org.apache.velocity.tools.view.VelocityViewServlet</servlet-class>
<init-param>
<param-name>org.apache.velocity.toolbox</param-name>
<param-value>/WEB-INF/tools.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>velocity</servlet-name>
<url-pattern>*.vm</url-pattern>
</servlet-mapping>
</web-app>
該配置表示攔截所有的vm結(jié)尾的請求 , vm就是velocity模板文件的擴(kuò)展名
2-3、引入配置文件
在web.xml中可以引入的配置文件有兩個 :
- tools.xml : 配置頁面使用的一些工具
- velocity.properties : 配置一些日志, 編碼, 宏等一些配置
如果要引入配置文件, 官方建議將配置文件放置在web項目的/WEB-INF目錄下
2-3-1配置文件一:tools.xml
<?xml version="1.0" encoding="UTF-8"?>
<tools>
<toolbox scope="application">
<tool key="date" class="org.apache.velocity.tools.generic.DateTool" format="yyyy-MM-dd"></tool>
<tool key="number" class="org.apache.velocity.tools.generic.NumberTool" />
<tool key="math" class="org.apache.velocity.tools.generic.MathTool" />
<tool key="display" class="org.apache.velocity.tools.generic.DisplayTool"/>
<tool key="esc" class="org.apache.velocity.tools.generic.EscapeTool"/>
<tool key="field" class="org.apache.velocity.tools.generic.FieldTool" include="com.kk.constants.MyConstants"/>
<tool key="class" class="org.apache.velocity.tools.generic.ClassTool" inspect="com.kk.utils.Result" ></tool>
<tool key="sorter" class="org.apache.velocity.tools.generic.SortTool"/>
<tool key="collection" class="org.apache.velocity.tools.generic.CollectionTool" stringsDelimiter=" "></tool>
<tool key="xml" class="org.apache.velocity.tools.generic.XmlTool" resource="xml/user.xml"/>
</toolbox>
<toolbox scope="request">
<tool key="context" class="org.apache.velocity.tools.generic.ContextTool"/>
<tool key="render" class="org.apache.velocity.tools.generic.RenderTool"></tool>
</toolbox>
</tools>
2-3-2配置文件二:tools.xml
官網(wǎng)截取,具體看官網(wǎng)(寫法改成properties即可):http://velocity.apache.org/engine/devel/configuration.html#configuration-summary-tree
context. +-- scope_control. +-- define = false
| +-- evaluate = false
| +-- foreach = true
| +-- macro = false
| +-- template = false
| +-- *somebodymacro* = false
+-- self_reference_key = *key_name*
directive. +-- define.max_depth = 2
+-- foreach. +-- max_loops = -1
| +-- skip_invalid = true
+-- if.empty_check = true
+-- parse.max_depth = 10
event_handler. +-- include.class = *classname*, *classname* ...
+-- invalid_reference. +-- class = *classname*, *classname* ...
+-- exception = false
+-- null = false
+-- quiet = false
+-- tested = false
+-- method_exception.class = *classname*, *classname* ...
+-- reference_insertion.class = *classname*, *classname* ...
introspector. +-- conversion_handler. +-- class = org.apache.velocity.util.introspection.TypeConversionHandlerImpl
| +-- instance = *Java Object instance*
+-- uberspect.class = org.apache.velocity.util.introspection.UberspectImpl
parser. +-- allow_hyphen_in_identifiers = false
+-- pool. +-- class = org.apache.velocity.runtime.ParserPoolImpl
| +-- size = 20
+-- space_gobbling = lines
resource. +-- default_encoding = UTF-8
+-- loaders = file, ...
+-- loader.*loader_name*. +-- class = *classname*
| +-- instance = *Java Object instance*
| +-- cache = false
| +-- modification_check_interval = 2
| +-- *loader_prop* = ...
+-- manager. +-- cache. +-- class = org.apache.velocity.runtime.resource.ResourceCacheImpl
| +-- default_size = 89
+-- class = org.apache.velocity.runtime.resource.ResourceManagerImpl
+-- instance = null
+-- log_when_found = true
runtime. +-- custom_directives = *classname*, *classname* ...
+-- interpolate_string_literals = true
+-- log. +-- instance = *Java Object instance*
| +-- log_invalid_method_calls = true
| +-- log_invalid_references = true
| +-- name = org.apache.velocity
| +-- track_location = false
+-- strict_math = false
+-- strict_mode. +-- enable = false
| +-- escape = false
+--string_interning = true
velocimacro. +-- arguments.strict = false
+-- body_reference = false
+-- enable_bc_mode = false
+-- inline. +-- allow = true
| +-- local_scope = false
| +-- replace_global = false
+-- library. +-- autoreload = false
+-- path = velocimacros.vtl
3、案例:使用 Velocity View
當(dāng)我們配置好了之后使用VelocityView非常簡單 , 只需要將數(shù)據(jù)保存在web項目的域中 , 在velocity模板中就可以直接獲取數(shù)據(jù)展示了
3-1、展示基礎(chǔ)數(shù)據(jù)
3-1-1、編寫模板:在web項目下創(chuàng)建user-info.vm模板文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
歡迎您: $name
</body>
</html>
3-1-2、創(chuàng)建Servlet
public class UserInfoServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//在request域保存數(shù)據(jù)
request.setAttribute("name",request.getParameter("name"));
//設(shè)置響應(yīng)數(shù)據(jù)格式以及字符集
response.setContentType("text/html;charset=utf-8");
request.getRequestDispatcher("/vms/user-info.vm").forward(request,response);
}
}
3-1-3、配置Servlet
<servlet>
<servlet-name>UserInfoServlet</servlet-name>
<servlet-class>com.kk.servlet.UserInfoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserInfoServlet</servlet-name>
<url-pattern>/user/info</url-pattern>
</servlet-mapping
3-2、展示列表數(shù)據(jù)
3-2-1、編寫模板:在項目下創(chuàng)建user-list.vm用于展示列表數(shù)據(jù)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table>
<tr>
<td>編號</td>
<td>姓名</td>
<td>性別</td>
<td>年齡</td>
<td>操作</td>
</tr>
#foreach($user in $userList)
<tr>
<td>$foreach.index</td>
<td>$user.name</td>
<td>$user.sex</td>
<td>$user.age</td>
<td>
<a href="">編輯</a>
<a href="">刪除</a>
</td>
</tr>
#end
</table>
</body>
</html>
3-2-2、創(chuàng)建Servlet
public class UserListServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<User> userList = new ArrayList<User>();
userList.add(new User("呂布",38,"man"));
userList.add(new User("貂蟬",16,"woman"));
userList.add(new User("劉備",28,"man"));
userList.add(new User("關(guān)羽",25,"man"));
userList.add(new User("張飛",20,"man"));
userList.add(new User("甄宓",21,"woman"));
request.setAttribute("userList",userList);
response.setContentType("text/html;charset=utf-8");
request.getRequestDispatcher("/vms/user-list.vm").forward(request,response);
}
}
3-2-3、配置Servlet
<servlet>
<servlet-name>UserListServlet</servlet-name>
<servlet-class>com.kk.servlet.UserListServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserListServlet</servlet-name>
<url-pattern>/user/list</url-pattern>
</servlet-mapping>
3-3、使用Tools工具
因為我們在配置VelocityViewServlet的時候已經(jīng)加載了tools.xml配置文件 , 所以直接在模板文件中使用工具即可
例如 : 列表頁面我們展示編號使用的是$foreach.index , 是從0開始的, 現(xiàn)在想讓編號從1開始 , 可以使用MathTool , 在index的基礎(chǔ)上+1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table>
<tr>
<td>編號</td>
<td>姓名</td>
</tr>
#foreach($user in $userList)
<tr>
<td>$math.add($foreach.index,1)</td>
<td>$user.name</td>
</tr>
#end
</table>
</body>
</html>
4、工具類及案例
4-1、CookieTool:用于獲取和創(chuàng)建Cookie
模板:
<body>
$cookie.username ## 獲取指定名稱的cookie值
$cookie.add("phone",'18917009089') ## 創(chuàng)建并設(shè)置cookie
</body>
配置:
<toolbox scope="request">
<tool key="cookie" class="org.apache.velocity.tools.view.CookieTool"/>
</toolbox>
4-2、BrowserTool:用于獲取客戶端瀏覽器,操作系統(tǒng),設(shè)備,語言等信息。
模板:
<body>
設(shè)備信息 : $browser.device <br>
用戶客戶端 : $browser.userAgentString <br>
渲染引擎 : $browser.renderingEngine.name<br>
操作系統(tǒng) : $browser.operatingSystem.name<br>
IP地址 : $browser.iPAddress<br>
</body>
配置:
<toolbox scope="session">
<tool key="browser" class="org.apache.velocity.tools.view.BrowserTool" />
</toolbox>
可以定義在在request和session范圍 , 建議在session范圍使用
servlet:
public class BrowserToolServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.getRequestDispatcher("/vms/tool-browser.vm").forward(request,response);
}
}
<servlet>
<servlet-name>BrowserToolServlet</servlet-name>
<servlet-class>com.kk.servlet.BrowserToolServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BrowserToolServlet</servlet-name>
<url-pattern>/user/browser</url-pattern>
</servlet-mapping>
4-3、ParameterTool:用戶獲取請求中的參數(shù)
模板:
<body>
## 獲取所有的請求參數(shù)
#set($parameters = $params.all)
#foreach($entry in $parameters.entrySet())
$entry.key : $entry.value <br>
#end
<hr>
## 獲取一個key對應(yīng)一個值的參數(shù)
name : $params.getString("username") <br>
## 獲取一個key對應(yīng)多個值得參數(shù)
hobby : $params.getStrings("hobby")
</body>
配置:
<toolbox scope="request">
<tool key="params" class="org.apache.velocity.tools.view.ParameterTool"/>
</toolbox>
4-4、ViewContextTool:
ViewContextTool是GenericTools中ContextTool的擴(kuò)展 , 可以Velocity容器中的所有數(shù)據(jù) , 包括HttpServletRequest, HttpSession and ServletContext中的數(shù)據(jù)
模板:
<body>
## 獲取velocity容器中的所有數(shù)據(jù)
#foreach( $key in $context.keys )
$key = $context.get($key) <br>
#end
</body>
配置:
<toolbox scope="request">
<!-- <tool key="context" class="org.apache.velocity.tools.generic.ContextTool"/>-->
<tool key="context" class="org.apache.velocity.tools.view.ViewContextTool"/>
</toolbox>
四、自定義tools工具類
VelocityTools中定義了很多Tools供我們使用 , 如果官方提供的還不能滿足我們的需求, 我們也可以自己定義工具類 , 自定義工具類有一些要求 , 如下 :
- 工具類必須聲明為public
- 工具類中必須提供公共的無參構(gòu)造方法
下面我們可以定義一個字符串的Tools類, 幫助我們對字符串進(jìn)行特殊的處理 , 主要有二個功能
- 判斷字符串是否為Null或者""
- 隨機(jī)生成一個指定位數(shù)的數(shù)字字符串
1、編寫工具類
package com.kk.tools;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.velocity.tools.config.DefaultKey;
import org.apache.velocity.tools.config.InvalidScope;
import org.apache.velocity.tools.config.ValidScope;
@DefaultKey("strings")
@ValidScope({"application","request","session"})
public class StringsTools {
/**
* 判斷字符串是否為空
* @param str
* @return
*/
public boolean isEmpty(String str){
if(str==null || "".equals(str)){
return true ;
}
return false ;
}
/**
* 生成一個指定位數(shù)的隨機(jī)字符串
* @param count
* @return
*/
public String randomNumeric(int count){
return RandomStringUtils.randomNumeric(count) ;
}
}
@DefaultKey : 用于指定默認(rèn)的key
@ValidScope : 用于指定可用的作用范圍
2、配置工具類
<toolbox scope="application">
<tool key="strings" class="com.kk.tools.StringsTools" />
</toolbox>
3、使用工具類
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
判斷字符串是否為空 : $strings.isEmpty("") <br>
隨機(jī)生成數(shù)字字符串 : $strings.randomNumeric(6);
</body>
</html>
4、編寫Serlvet
public class StringsToolServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
request.getRequestDispatcher("/vms/tool-strings.vm").forward(request,response);
}
}
其實直接訪問就可以, 但是我們模板中有中文, 需要在serlvet中設(shè)置響應(yīng)數(shù)據(jù)的字符集 , 否則會有亂碼
五、★springmvc整合velocity(頁面靜態(tài)化)
我們之前已經(jīng)在Servlet中使用velocity作為我們的視圖展示數(shù)據(jù) , 但是在開發(fā)過程中我們一般會使用框架來進(jìn)行web開發(fā), 提高我們的開發(fā)效率 , 所以下面我們來說一說在SpringMVC框架中如何使用Velocity作為視圖展示數(shù)據(jù)
1、步驟分析
在SpringMVC中使用Velocity非常簡單 , 主要有以下步驟
- 搭建springmvc開發(fā)環(huán)境
- 引入velocity依賴
- 配置Velocity開發(fā)環(huán)境
- 編寫Velocity模板
- 編寫springmvc控制器
2、具體步驟
2-1、搭建springmvc開發(fā)環(huán)境
2-1-1、添加依賴
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-api</artifactId>
<version>7.0.37</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>8</source>
<target>8</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<port>8080</port>
<uriEncoding>utf-8</uriEncoding>
</configuration>
</plugin>
</plugins>
</build>
2-1-2、配置web.xml配置
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
2-1-3、配置springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--開啟組件掃描-->
<context:component-scan base-package="com.kk"></context:component-scan>
<!--開啟注解驅(qū)動-->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
2-2、SpringMVC整合Velocity
2-2-1、添加依賴
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.apache.velocity.tools</groupId>
<artifactId>velocity-tools-generic</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>org.apache.velocity.tools</groupId>
<artifactId>velocity-tools-view</artifactId>
<version>3.0</version>
</dependency>
2-2-2、引入Tools配置文件:在/WEB-INF/下創(chuàng)建并編寫tools.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<tools>
<toolbox scope="application">
<tool key="date" class="org.apache.velocity.tools.generic.DateTool" format="yyyy-MM-dd"></tool>
<tool key="number" class="org.apache.velocity.tools.generic.NumberTool" />
<tool key="math" class="org.apache.velocity.tools.generic.MathTool" />
</toolbox>
</tools>
這個需要根據(jù)項目中使用的工具自己配置, 目前入門案例我們簡單配置幾個即可
2-2-3、配置web.xml配置:在web.xml中配置VelocityViewServlet
<servlet>
<servlet-name>velocity</servlet-name>
<servlet-class>org.apache.velocity.tools.view.VelocityViewServlet</servlet-class>
<init-param>
<param-name>org.apache.velocity.toolbox</param-name>
<param-value>/WEB-INF/tools.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>velocity</servlet-name>
<url-pattern>*.vm</url-pattern>
</servlet-mapping>
2-2-4、配置視圖解析器:因為我們現(xiàn)在使用velocity充當(dāng)SpringMVC的視圖解析器 , 所以需要配置視圖解析器, 指定視圖模板文件的位置及擴(kuò)展名
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/vms/"></property>
<property name="suffix" value=".vm"></property>
</bean>
2-3、編寫Velocity模板:在/vms/目錄下創(chuàng)建user-list.vm模板文件 , 用于展示列表數(shù)據(jù)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table>
<tr>
<td>編號</td>
<td>姓名</td>
</tr>
#foreach($user in $userList)
<tr>
<td>$math.add($foreach.index,1)</td>
<td>$user.name</td>
</tr>
#end
</table>
</body>
</html>
2-4、創(chuàng)建實體類
public class User {
private String name ;
private Integer age ;
private String sex ;
}
2-5、編寫springmvc控制器
@Controller
@RequestMapping(path = "/user")
public class UserController {
@RequestMapping(path = "/list")
public String list(Model model){
List<User> userList = new ArrayList<User>();
userList.add(new User("呂布",38,"man"));
userList.add(new User("貂蟬",16,"woman"));
userList.add(new User("劉備",28,"man"));
model.addAttribute("userList",userList);
return "user-list";
}
}
因為我們配置了SpringMVC的視圖解析器 , 所以控制方法返回視圖名稱字符串即可, 視圖解析器會自動拼接完整視圖路徑 , 展示數(shù)據(jù)
2-6、訪問測試:http://localhost:8080/user/list
六、綜合案例
SSM+Velocity來實現(xiàn)用戶數(shù)據(jù)增刪改查