<!--[if !supportLists]-->1. <!--[endif]-->JET
<!--[if !supportLists]-->a) <!--[endif]-->说明:JET是一个开源的代码生成引擎,她使用一种类似JSP的语法来书写模板,模板文件会被JET引擎转换为模板实现类,用户使用模板实现类,来生成所需的目标代码。
<!--[if !supportLists]-->b) <!--[endif]-->流程:
JET模板 |
模板实现类 |
应用程序 |
所需代码 |
<!--[if !supportLists]-->2. <!--[endif]-->JET语法:
<!--[if !supportLists]-->a) <!--[endif]-->声明JET模板:
<!--[if !supportLists]--> i. <!--[endif]-->.txtjet文件:
<%@jet package="org.nick.jet" class="HelloWorld" %>
Hello World
<!--[if !supportLists]--> ii. <!--[endif]-->模板实现类:
package org.nick.jet;
public class HelloWorld{
protected final String NL = System.getProperties().
getProperty("line.separator");
protected final String TEXT_1 = "Hello World";
protected final String TEXT_2 = NL;
public String generate(Object argument){
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(TEXT_1);
stringBuffer.append(TEXT_2);
return stringBuffer.toString();
}
}
<!--[if !supportLists]--> iii. <!--[endif]-->应用程序:
public class HelloWorldTest {
public static void main(String[] args) {
HelloWorld template = new HelloWorld();
System.out.println(template.generate(null));
}
}
<!--[if !supportLists]--> iv. <!--[endif]-->输出结果:
Hello World
<!--[if !supportLists]--> v. <!--[endif]-->说明:JET模板文件必须声明后缀为.txtjet的文件。JET模板文件的开始必须声明<%@jet%>标签。上述演示了一个JET的简单使用。首先我们需要书写JET模板,该模板随后将会自动的被转换为模板实现类,然后在应用程序当中,我们只需实例化该实现类,并调用generate()方法即可。
<!--[if !supportLists]-->b) <!--[endif]-->输入参数:
<!--[if !supportLists]--> i. <!--[endif]-->.txtjet文件:
<%@jet package="org.nick.jet" class="HelloWorld" %>
Hello World,<%=argument%>!
<!--[if !supportLists]--> ii. <!--[endif]-->应用程序:
public class HelloWorldTest {
public static void main(String[] args) {
HelloWorld template = new HelloWorld();
System.out.println(template.generate("nick"));
}
}
<!--[if !supportLists]--> iii. <!--[endif]-->输出:
Hello World,nick!
<!--[if !supportLists]--> iv. <!--[endif]-->说明:我们可以通过模板实现类的generate()方法来向模板传入参数,而在模板文件当中,该参数可以通过argument变量来引用。虽然generate()的参数只是Object,但由于Java当中所有都是对象,包括数组,所以,但我们需要传入多个参数时,可以把他们作为一个Object[]数组传入,然后在模板中再强制转换回来。
<!--[if !supportLists]-->c) <!--[endif]-->模板文件中的全局变量:
<!--[if !supportLists]--> i. <!--[endif]-->说明:JET的模板文件定义了两个全局变量,argument和stringBuffer,因此,我们可以像上文那样,在模板文件当中,对他们进行直接的操作。
<!--[if !supportLists]-->d) <!--[endif]-->模板包含:
<!--[if !supportLists]--> i. <!--[endif]-->说明:通过<%@include file=""%>标签,我们可以在模板文件中引入其他文件,如果被引入文件内部含有JET指令,则该指令也将被解释。
<!--[if !supportLists]-->e) <!--[endif]--><%@jet%>中的其他属性:
<!--[if !supportLists]--> i. <!--[endif]-->说明:在<%@jet%>标签当中,除了上文所演示的package和class属性以外,还有以下几个可选属性。imports,用于导入模板文件中需要用到的类;startTag和endTag,由于JET模板文件默认使用“<%”和“%>”作为JET指令的开始和结束标记,而当我们需要用JET来生成类似JSP那样的文件时,这将导致一些问题,为此,JET提供了startTag和endTag属性,用于修改JET指令的默认开始和结束标记;skeleton,在JET模板转换为实现类的过程中,系统都是使用一个默认的成为skeleton的文件来对模板进行翻译,而有的时候,我们可能希望对这个skeleton进行一些定制和重新指定,这就可以通过skeleton属性来完成。