import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.log4j.Category;
import org.apache.log4j.BasicConfigurator;
public class Log4jCategoryExample
{
public static String CATEGORY_NAME = "velexample";
public static void main( String args[] )
throws Exception
{
/*
* configure log4j to log to console
*/
BasicConfigurator.configure();
Category log = Category.getInstance( CATEGORY_NAME );
log.info("Hello from Log4jCategoryExample - ready to start velocity");
/*
* now create a new VelocityEngine instance, and
* configure it to use the category
*/
VelocityEngine ve = new VelocityEngine();
ve.setProperty( RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
"org.apache.velocity.runtime.log.SimpleLog4JLogSystem" );
ve.setProperty("runtime.log.logsystem.log4j.category", CATEGORY_NAME);
ve.init();
log.info("this should follow the initialization output from velocity");
}
}
上面的例子可以在examples/logger_example.下找到.
2.Simple Example of a Custom Logger
这是一个定制实现你自己的日志记录器,并将其加入到Velocity的日志系统中. LogSystem interface—只需要支持这个接口.
import org.apache.velocity.runtime.log.LogSystem;
import org.apache.velocity.runtime.RuntimeServices;
...
public class MyClass implements LogSystem
{
...
{
...
try
{
/*
* register this class as a logger
*/
Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, this );
Velocity.init();
}
catch (Exception e)
{
/*
* do something
*/
}
}
/**
* This init() will be invoked once by the LogManager
* to give you current RuntimeServices intance
*/
public void init( RuntimeServices rsvc )
{
// do nothing
}
/**
* This is the method that you implement for Velocity to call
* with log messages.
*/
public void logVelocityMessage(int level, String message)
{
/* do something useful */
}
...
}
12.Configuring Resource Loaders(资源装载器配置)
1.Resource Loaders
Velocity一个非常重要的基础功能是资源管理和装载. 这里资源 'resources' 不仅包括了模板('templates'),RMS也可以处理非模板文件, 特别是在使用 #include() 指令时.
resource loader system (资源装载系统)很容易扩展,可以同时执行多个资源装载器的操作. 这极大的方便了资源管理, --你可以根据需要,定制自己的资源装载器.
Velocity当前包含4种资源管理器, 说明如下:(注意例程中的配置参数有一个loader配置名 (ex.'file' in file.resource.loader.path).这个 'common name' 配置不一定会在你的系统中工作. 具体可见 resource configuration properties 理解系统如何工作. 这每一个loader都在包 org.apache.velocity.runtime.resource.loader. 中
FileResourceLoader : 这个loader从文件系统取得资源,其配置参数如下:
file.resource.loader.path =
file.resource.loader.cache = true/false
file.resource.loader.modificationCheckInterval =
这是己配置的默认装载器, 默认从当前目录('current directory'). 但当你不想将模板入到servlet容器的启动目录下时,这个loader就无能为力了。请参看 developing servlets with Velocity.
JarResourceLoader : 这个loader可以从jar文件包中取得资源,在你把你的模板文件全部打包成 jar包时,系统会用这个loader来提取. 配置基本一样除过jar.resource.loader.path, 这里或以使用标准的JAR URL syntax of java.net.JarURLConnection.
ClasspathResourceLoader : 从classloader中取得资源. 一般来说,这意味着ClasspathResourceLoader将从classpath中load templates.这是