Compiling JSPs

When deploying to servers, the jspc task can be useful. This task runs the JavaServer Pages compiler and turns JSP pages into Java source, which you can compile with the javac task. Compiling JSP pages supports fast invocation of JSP pages, deployment on servers without the complete JDK, or lets you check the syntax of pages without deploying them. By default, this task uses the Jasper JSP compiler, which comes with Tomcat. Copy Tomcat's jasper-compiler.jar and jasper-runtime.jar files into the Ant lib directory to use this task. You'll need servlet.jar, which comes with Tomcat, in the Ant lib directory.

For example, say you have this JSP page, greeting.jsp:

<HTML>
  <HEAD>
    <TITLE>Creating a Greeting</TITLE>
  </HEAD>

  <BODY>
    <H1>Creating a Greeting</H1>
    <%
        out.println("Hello from JSP!");    //Display the greeting
     %>
  </BODY>
</HTML>

Example 8-5 shows how to compile this JSP into greeting.java.

Example 8-5. Compiling JSP pages (ch08/jspc/build.xml)

<?xml version="1.0" ?>
<project default="main">

    <property name="message" value="Compiling the JSP...." />
    <property name="src" location="source" />
    <property name="output" location="bin" />

    <target name="main" depends="init, compile">
        <echo>
            ${message}
        </echo>
    </target>
  
    <target name="init">
        <mkdir dir="${output}" />
    </target>
  
    <target name="compile">
        <jspc srcdir="${src}"
            destdir="${output}"
            package="org.antbook.jsp"
            verbose="9">
            <include name="**/*.jsp" />
        </jspc>
    </target>
  
</project>

Here's what you see when you run the build ...

Get Ant: The Definitive Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.