velocity的几层窗户纸velocity的几层窗户纸 分类:开源这几天有一个项目要使用velocity来生成文件,遇到了一些问题,最后也辗转找到了解决的方法。用一个朋友的话说,这就是一层窗户纸。
开发环境:Tomcat5.5,Velocity-1.4
1、velocity模版和配置文件的位置
为了测试方便,我首先把根据模版生成文件的源代码单独拿出来,代码(省去了无关的代码)如下:
//FileManager.java
//初始化方法,获得属性配置
private void init() {
try {
Velocity.init("velocity.properties");
} catch(Exception e) {
System.out.println("初始化时发生错误!");
e.printStackTrace();
}
}
/**
* 根据模板建立文件
*/
public boolean createFile(String bt, String content, String[] tp, String fileName) {
//是否创建成功
boolean isCreateSuccess = true;
try {
//建立模版
VelocityContext context = new VelocityContext();
//设置各个变量
//…
//得到模版
Template template = Velocity.getTemplate("news.vm");
//写入文件
//…
} catch (Exception e) {
//异常处理
//…
}
}
这里配置文件是:velocity.properties,模版文件:news.vm,它们和FileManager的package在同一个目录下,如:
FileManager的package为com.bokee.mydeman,FileManager.class的位置是C:/1/com/bokee/mydeman/FileManager.class,那么velocity.properties和news.vm的路径就是C:/1/velocity.properties和C:/1/news.vm;如果FileManager没有声明package,那么配置文件和模版文件就和FileManager.class在同一个目录下。
按照以上规则,测试通过。于是移植到Tomcat下面,可是配置文件和模版文件应该放在什么地方呢?按照上面的规则,它们就应该在WEB-INF/classes下,可是实际运行却报出无法找到资源的异常。于是就把它们分别放在了web工程根目录下、WEB-INF下等几个位置,均报同样的异常。google一下,发现竟然要放在system32下,呵呵,这样放置程序如何移植?于是决定自己指定它们的路径,修改后的程序如下:
//
public class FileManager {
private String config = "";
//构造函数中指定配置文件和模版文件所在的路径
public FileManager(String config) {
this.config = config;
init();
}
/**
* 初始化模版
*/
private void init() {
//…
Velocity.init(config + "/velocity.properties");
//…
}
/**
* 根据模板建立文件
*/
public boolean createFile(String bt, String content, String[] tp, String fileName) {
//…
Template template = Velocity.getTemplate(config + "/news.vm");
//…
}
}
保存测试,init()方法顺利通过,可是模版仍然报出无法找到资源的异常。呜呼,只有google了,说是要使用Velocity的ResourceEngine来加载资源,否则找不到vm文件。按照指示修改源代码,如下:
VelocityEngine engine = new VelocityEngine();
Properties properties = new Properties();
properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, config);
engine.init(properties);
Template template = engine.getTemplate("news.vm");
重新运行测试,OK!
2、模版的中文问题
Java的中文问题像一个幽灵一样总是在程序员的周围转来转去,不定什么时候就会出来骚扰一下。
news.vm中使用了中文的字符串,在生成的文件中总是会变成莫名其妙的乱码。查阅Velocity的Developer's Guide文档,在Velocity Configuration Keys and Values一节中给出了具体的解决方法,使用input.encoding和output.encoding指定输入和输出的编码格式(默认的是ISO-8859-1),于是在velocity.properties中分别指定二者的值:
input.encoding = GBK
output.encoding = GBK
单独测试通过,可以正确输出中文。可是在Tomcat中无论如何都出不来中文,把这两个属性值在ISO-8859-1、UTF-8和GBK中变换了无数次,仍然是乱码。最后向高人求教,修改源代码为:
Template template = engine.getTemplate("news.vm","GBK");
呵呵,一切OK!中文正常显示,向其道谢,笑称“一层窗户纸”。