`

velocity使用步骤

阅读更多
缓存技术:
1:页面html静态化(效率最高,不用请求action);
2:页面缓存(不用请求业务层);
3:二级缓存(减少与数据库交互);
4:数据源(在连接池放置连接对象,减少连接对象的频繁创建)
5:SSI(抽象页面内容,例如公共的页面头部,或者尾部)

velocity的使用属于是页面html的静态化技术。
如果要在生成的html文件里动态统计总数之类的操作,使用<img src="/count.action?id=1" width="0" height="0"/>这个小技巧

velocity的使用步骤:
1:导入jar包和相关的依赖包
2:配置velocity配置文件(在src目录下添加velocity.properties文件),或者也可以用Properties对象。
    #Velocity.properties\u914D\u7F6E\u793A\u4F8B 
//在类路径下配置模板,去掉前面的#号
    #resource.loader=class      #class.resource.loader.class=org.apache.Velocity.runtime.resource.loader.ClasspathResourceLoader

//在指定目录下配置模板
    resource.loader=file  
    file.resource.loader.path=D:\Workspaces\MyEclipse 8.5\velocity\WebRoot\WEB-INF\velocityTempalte
    file.resource.loader.cache=false  
//指定输入编码
   input.encoding=UTF-8 
//指定输出编码
    output.encoding=UTF-8 
//可以用做web技术的视图技术,指定返回给浏览器的编码
    #default.contentType=text/html;charset\=UTF-8


在模板路径下创建模板(message.vm):
${message.id}---${message.title}--${message.content}


public class VelocityUtil {

private static Boolean state=false;
public static void display(Message messages,File dir) {
if(!state){
Properties properties=new Properties();
properties.put("resource.loader=file","file");
properties.put("file.resource.loader.path","F:\\myclipse\\velocity\\src\\template");
properties.put("input.encoding","UTF-8");
properties.put("output.encoding","UTF-8");
Velocity.init(properties);
}

try{
VelocityContext context=new VelocityContext();
context.put("messages",messages);
if(!dir.exists()){
dir.mkdirs();
}

Template template=Velocity.getTemplate("message.vm");

FileOutputStream stream=new FileOutputStream(new File(dir,messages.getId()+".html"));
OutputStreamWriter out=new OutputStreamWriter(stream);
BufferedWriter writer=new BufferedWriter(out);
template.merge(context, writer);
writer.flush();
writer.close();
}catch(Exception e){
e.printStackTrace();
}

}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics