让Web项目中Velocity的#parse支持相对路径
来源:互联网 发布:linux挂载分区命令 编辑:程序博客网 时间:2024/06/05 02:22
下面这个宏可以让你在web项目中使用相对路径来包含其他的模板文件
#macro(invoke $page)
#if($page.startsWith("/"))
#parse($page)
#else
#set($uri = $request.getAttribute("javax.servlet.include.request_uri"))
#if(!$uri)#set($uri = $request.getServletPath())#end
#set($path = $uri.substring(0, $uri.lastIndexOf("/")))
#parse("$path/$page")
#end
#end
把这段代码加在VM_global_library.vm中,你就可以在页面模板中用#invoke("head.vm")来在页面中嵌入其他的模板文件,比起用#parse指定绝对路径省事很多。
不过这种做法有一个缺点:当子页面还欠有其他页面的时候,相对路径就有点问题,是相对于主页面而非当前页面,这也会给使用上造成一些困扰,但解决的办法还是有的,相对比较复杂而已。
首先我们需要编写一个Toolbox类,例如MyVelocityTool,该类实现接口ViewTool,代码如下:
public class MyVelocityTool implements ViewTool {
protected HttpServletRequest request;
protected HttpServletResponse response;
protected ServletContext context;
protected VelocityContext velocity;
/*
* Initialize toolbox
* @see org.apache.velocity.tools.view.tools.ViewTool#init(java.lang.Object)
*/
public void init(Object arg0) {
if(arg0 instanceof ViewContext){
ViewContext viewContext = (ViewContext) arg0;
request = viewContext.getRequest();
response = viewContext.getResponse();
context = viewContext.getServletContext();
velocity = (VelocityContext)viewContext.getVelocityContext();
}
else if(arg0 instanceof ServletContext){
context = (ServletContext)arg0;
}
}
public String current_template(){
return velocity.getCurrentTemplateName();
}
}
接着在velocity-toolbox.xml中定义这个Toolbox类
最后修改#invoke宏如下:
#macro(invoke $page)
#if($page.startsWith("/"))
#parse($page)
#else
#set($uri = $dlog.current_template())
#set($path = $uri.substring(0, $uri.lastIndexOf("/")))
#parse("$path/$page")
#end
#end
这就是一个可以完全使用相对路径的方法了,包括子页面嵌入其他的子页面,而不会造成使用的困扰。
- 让Web项目中Velocity的#parse支持相对路径
- 让Web项目中Velocity的#parse支持相对路径
- web项目中相对路径的问题
- web项目的中绝对路径和相对路径
- web项目中相对路径与绝对路径
- WEB项目的相对路径与绝对路径
- web项目的相对路径和绝对路径
- C# 中获取项目的相对路径
- java中项目的相对路径
- Java Web项目相对路径
- J2EE WEB项目中获取相对路径与绝对路径的方法
- (转)J2EE WEB项目中获取相对路径与绝对路径的方法
- java程序和web项目程序中相对路径的使用
- Eclipse的WEB项目>HTML/JSP中嵌入CSS样式表(相对路径)
- web 服务中相对路径
- web开发中相对路径
- 【N转ITeye】java项目中相对路径的获取(普通项目和web项目均有)
- IIS对于Web页中相对路径解析的问题
- Apache+SVN+Trac搭建项目管理服务器的安装与配置详解!
- 初学入门:如何有效编写软件的75条建议
- Unix下的解压命令 tar
- CSS 9宫格边框
- 字幕换色
- 让Web项目中Velocity的#parse支持相对路径
- 用Java动态代理实现AOP
- DELPHI中使用DLL的方法以及INSTALLSHIELD中使用DLL方法
- 恭贺新春, 祝大家新年快乐, 万事如意
- AutomatedQA AQTime v5.40.399
- Immunity Debugger v1.4
- ListView 自绘模式的一种实现
- 求逆矩阵的并行算法
- shell中的条件测试