Velocity的路径和乱码问题

Velocity

Velocity是一个基于java的模板引擎(template engine)。老家是:http://www.apache.org

今天使用中遇到了他的 路径找不到还有解析文件乱码的问题:

解决如下:

 1。 在初始化的时候设置一个路径的属性,并设置相应的输入编码和输出

 代码如下

try {
   Properties p = new Properties();
   p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, "c://");
   p.setProperty(Velocity.INPUT_ENCODING, "GBK");
   p.setProperty(Velocity.OUTPUT_ENCODING, "GBK");
   Velocity.init(p);
  } catch (Exception e) {
   System.out.println("Problem initializing Velocity : " + e);
   return null;
  }

  /* lets make a Context and put data into it */

  VelocityContext context = new VelocityContext();

.......

这样就一切ok了,注意GBK如果改成UTF-8会依然是乱码,其中原理不是

Velocity 中,系统路径表示的是 Velocity 引擎所使用的文件系统路径,用于加载模板文件或者读取资源文件等操作。系统路径可以是绝对路径或者相对路径,具体取决于使用时的上下文环境。 如果是在 web 应用程序中使用 Velocity,通常可以使用 ServletContext 对象来获取系统路径。在 ServletContext 中,可以通过调用 getRealPath() 方法来获取 web 应用程序在文件系统中的真实路径,然后将其作为系统路径传递给 Velocity 引擎。 例如,在 Servlet 中可以这样获取 ServletContext 对象并设置系统路径: ```java import org.apache.velocity.app.Velocity; import javax.servlet.ServletContext; import javax.servlet.http.HttpServlet; public class VelocityServlet extends HttpServlet { public void init() { ServletContext context = getServletContext(); // 获取 ServletContext 对象 String realPath = context.getRealPath("/"); // 获取 web 应用程序的真实路径 Velocity.setProperty("file.resource.loader.path", realPath); // 设置 Velocity 引擎的系统路径 Velocity.init(); // 初始化 Velocity 引擎 } } ``` 在上面的例子中,我们首先获取 ServletContext 对象,然后通过调用 getRealPath() 方法获取 web 应用程序的真实路径。接着,我们将真实路径设置为 Velocity 引擎的系统路径,最后调用 Velocity.init() 方法初始化 Velocity 引擎。 需要注意的是,在上面的例子中,我们将系统路径设置为 web 应用程序的根目录,这样 Velocity 引擎就会在根目录下寻找模板文件。如果需要寻找其他目录下的模板文件,可以将系统路径设置为该目录的路径
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值