Hi everyone,
Enclosed is a file that enables people to use Tomcat/Jasper as a code
generator. What is nice is that it invokes Tomcat/Jasper directly, so it
doesn't use Apache, ports, etc., and therefore can very easily be integrated
into an application.
It also lets you pass session variables that can then be used by the JSP
page to help generate code. Following is an example of how to use the
JspTemplateCompiler. The source file is enclosed. Enjoy!
Peter Yared
SunLabs
SunMicrosystems, Inc.
peter.yared(remove me)eng.sun.com
You can make a template like the following JSP:
<%@ page %>
<jsp:useBean id="packageName" scope="session" class="java.lang.String" />
<jsp:useBean id="className" scope="session" class="java.lang.String" />
<jsp:useBean id="myString" scope="session" class="java.lang.String" />
<% if (packageName != null && packageName.length() > 0) { %>
package <%= packageName %>;
<% } %>
public class <%= className %> {
public <%= className %>() {
}
public int returnCustomNumber() {
return <%= 3+3 %>;
}
public String returnSessionString() {
return "<%= myString %>";
}
}
Which is then used to generate a .java file:
import java.io.IOException;
import java.util.Hashtable;
import javax.servlet.ServletException;
import org.apache.jasper.JspTemplateCompiler;
public class ServletTest {
public ServletTest() {
try {
Hashtable properties = new Hashtable();
properties.put("myString", "Yo");
org.apache.jasper.JspTemplateCompiler.debug = true;
org.apache.jasper.JspTemplateCompiler.processTemplate("D:\\jsps\\My.jsp",
"D:\\jsps\\MyClass.java", null, "MyClass", properties, null, null, true);
}
catch (IOException e) {
e.printStackTrace();
}
catch (ServletException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ServletTest servletTest = new ServletTest();
}
}
|