Spring MVC 整合Velocity及用法说明
Velocity是一个基于java的模板引擎(template engine),它允许任何人仅仅简单的使用模板语言(template language)来引用由java代码定义的对象。
配置:
1.在pom.xml增加依赖的velocity包
1 2 3 4 5 | <dependency> <groupId>velocity< / groupId> <artifactId>velocity< / artifactId> <version> 1.5 < / version> < / dependency> |
2.在servlet-context.xml中增加以下内容,如果有jsp的配置先注释掉
1 2 3 4 5 6 7 8 9 10 | <beans:bean id = "velocityConfig" class = "org.springframework.web.servlet.view.velocity.VelocityConfigurer" > <beans: property name = "resourceLoaderPath" value = "/WEB-INF/views" / > <beans: property name = "configLocation" value = "classpath:common/velocity.properties" / > < / beans:bean> <beans:bean id = "velocityViewResolver" class = "org.springframework.web.servlet.view.velocity.VelocityViewResolver" > <beans: property name = "suffix" value = ".htm" / > < / beans:bean> |
3.在resources/common目录下创建velocity.properties
1 2 3 4 5 6 7 8 9 | #encoding input .encoding = UTF - 8 output.encoding = UTF - 8 contentType = text / html;charset = UTF - 8 #autoreload when vm changed file .resource.loader.cache = false file .resource.loader.modificationCheckInterval = 1 velocimacro.library.autoreload = false |
4.新建testController
1 2 3 4 5 6 7 8 9 10 | @RequestMapping (value = "/test" ) @Controller public class TestController { @RequestMapping (value = "/index" ) public String index(Model model) { String name = "tester" ; model.addAttribute( "name" , name); return "test/index" ; } } |
5.新建test/index.htm模板
1 2 3 4 5 6 7 | <html> <head> < / head> <body> hello $name! < / body> < / html> |
6.访问http://localhost/test/index
显示 hello tester!
---------------------------------------------------------------------------------------------------------------------------------------------------------------
Velocity的基本语法:
1、"#"用来标识Velocity的脚本语句,包括#set、#if 、#else、#end、#foreach、#end、#iinclude、#parse、#macro等;
如:
#if(info.imgs" border=0>
#else
<img src="noPhoto.jpg">
#end
2、"i、TagUtil.options(...)等。
3、"{}"用来明确标识Velocity变量;
比如在页面中,页面中有一个{someone}name。
4、"!"用来强制把不存在的变量显示为空白。
如当页面中包含msg字符。这是我们不希望的,为了把不存 在的变量或变量值为null的对象显示为空白,则只需要在变量名前加一个“!”号即可。
如:info in info.someList #end,环读取集合list中的对象
1 2 3 | #foreach( $info in $hotL包含文件#inclue("模板文件名")或#parse("模板文件名")st1) <a href = "/blog/list?&cid=$!info.cid" target = "_blank" >$!info.title< / a><br> #end |
上面的脚本表示循环遍历hotList1集合中的对象,并输出对象的相关内容。
6、包含文件#inclue("模板文件名")或#parse("模板文件名")
主要用于处理具有相同内容的页面,比如每个网站的顶部或尾部内容。
使用方法,可以参考EasyJF开源Blog及EasyJF开源论坛中的应用!
如:
1 | #parse("/blog/top.html")或#include("/blog/top.html") |
parse与include的区别在于,若包含的文件中有Velocity脚本标签,将会进一步解析,而include将原样显示。
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 分享4款.NET开源、免费、实用的商城系统
· 解决跨域问题的这6种方案,真香!
· 5. Nginx 负载均衡配置案例(附有详细截图说明++)
· Windows 提权-UAC 绕过