Page Compilation-Runtime View





10.3 Page Compilation—Runtime View

At the heart of JSP technology is the process used to take the JSP source and convert it to a runtime object that executes within a Web container. The specification states that a Java class is to be generated which implements the javax.servlet.jsp.HttpJspPage interface. This Java class, in most cases a servlet, defines a _jspService() method which will be called by the Web container to provide the runtime service.

Servlet to JSP method mapping.

Servlet Method Name

JSP Method Name

service()

_jspService()

init()

_jspInit()

destroy()

_jspDestroy()

In addition to _jspService(), the HttpJspPage class implements the other life cycle methods of a servlet. Figure shows the mapping between the servlet and JSP methods.

The process of parsing the JSP source, producing the Java class, and compiling it (to make it ready to be loaded into the servlet engine), is known as page compilation. For most Web containers, this page compilation service is provided by a servlet. The level of support is determined by the J2EE level of an installed Web module.

Each page compilation servlet has a number of initialization parameters which affect the behavior of the page compilation. One of the most important of these is the keepgenerated=true. Setting this parameter ensures that the generated class's source code is saved to the file system (not just the compiled byte code file). This is useful for the developer to gain a general understanding of how the JSP works and can also be referenced while debugging.

Setting the keepgenerated parameter is done using the Web deployment descriptor editor's extension page in WebSphere Studio. An optional parameter is scratchdir, which indicates where the source files will be kept.

This page compiler option (Figure) should be used only during development. It is not a good idea to keep the generated source for the JSPs during production because you could end up with a lot of unnecessary files—and delay page compilation.

5. Generating Java source from JSPs.

graphics/10fig05.jpg

To learn more aspects of the class generated from the JSP source, consider the Java source code file shown in Listing 10.1 whose _jspService() method created the output for the JSP presented in Figures 10.2 and 10.3.

Generated servlet source

public void _jspService(HttpServletRequest request, HttpServletResponse  response)

   throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;

    PageContext pageContext = null;

    HttpSession session = null;

    ServletContext application = null;

    ServletConfig config = null;

    JspWriter out = null;

    Object page = this;

    String  _value = null;

    java.util.Stack _jspxTagObjects = new java.util.Stack();

    try {

      if (_jspx_inited == false) {

        synchronized (this) {

          if (_jspx_inited == false) {

            _jspx_init();

            _jspx_inited = true;

          }

        }

      }

      _jspxFactory = JspFactory.getDefaultFactory();

      response.setContentType("text/html; charset=ISO-8859-1");

      pageContext = _jspxFactory.getPageContext(this, request, response,

                     "", true, 8192, true);



      application = pageContext.getServletContext();

      config = pageContext.getServletConfig();

      session = pageContext.getSession();

      out = pageContext.getOut();

     // begin [file="/book_simple.jsp";from=(0,0);to=(3,0)]

     out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01

         transitional//EN\">\r\n<HTML>\r\n<HEAD>\r\n");

      // end



      // begin [file="/book_simple.jsp";from=(7,2);to=(16,0)]

      out.write("\r\n<META http-equiv=\"Content-Type\" content=\"text/html;

         charset=ISO-8859-1\">\r\n<META name=\"GENERATOR\" content=\"IBM

         WebSphere Studio\">\r\n<TITLE>Simple

         JSP</TITLE>\r\n</HEAD>\r\n<BODY bgcolor=\"teal\"

         text=\"yellow\">\r\n<H1 align=\"center\">Thank you for visiting our

         site</H1>\r\n<H2>You had contact with our server at:</H2>\r\n<center>

         <H2>\r\n");

      // end



      // begin [file="/book_simple.jsp";from=(16,3);to=(16,25)]

       out.print( new java.util.Date() );

      // end

      // begin [file="/book_simple.jsp";from=(16,27);to=(19,0)]

        out.write("</H2>\r\n</BODY>\r\n</HTML>\r\n");

      // end

    } catch (Throwable t) {

      if (out != null && out.getBufferSize() != 0)

        out.clearBuffer();

      if (pageContext != null) pageContext.handlePageException(t);

    } finally {

      while (_jspxTagObjects.empty() == false){

        ((javax.servlet.jsp.tagext.Tag)_jspxTagObjects.pop()).release();

      }

      if (_jspxFactory != null) _jspxFactory.releasePageContext(pageContext);



      /* Service Finally Phase */

    }

  }

}

The package statement and several import statements were dropped from the file listing, as were the generated _jspInit() and _jspDestroy() methods. For this simple JSP, everything of interest appears in _jspService(). The initial part of this method defines a number of local variables that are later initialized from utility methods on the class, PageContext. Immediately after defining the local variables, one-time behavior (calling _jspx_init()) is invoked.

After the initialization of the JSP the service method proceeds to output both the static and dynamic parts of the page interleaving between them as necessary to maintain the structure of the page. The static elements are represented by strings and sent to the output stream using simple out.write() methods, where out is an object of type PrintWriter. The dynamic part of the page is converted into the appropriate Java code from the original JSP expression or scriptlet.[2] In the case of our example the JSP expression:

[2] Scriptlets, along with other elements of JSP syntax, are discussed later in this chapter.





<%= new java.util.Date() %>

was converted to:





out.print( new java.util.Date() );

There are also a number of comments, inserted by the page compiler, which document the source of the static content for the page, such as the file containing the HTML, including starting and ending row and column position.

The HttpJspPage interface also defines two methods—jspInit() and jspDestroy(). These methods can be overridden if the JSP needs to perform any one-time initialization or termination behavior. When the generated class is a servlet, the superclass (provided by the page compilation service) will override the HttpServlet's service() method so that its behavior is to call _jspService(). Similarly, the HttpServlet's init() method will call jspInit()and destroy()will call jspDestroy(). In this way, the servlet engine's control model gets mapped to the JSP runtime model (as specified in the HttpJspPage interface).

Page compilation occurs if no servlet class has yet been generated for the target JSP or if the currently available servlet class' creation date (time stamp) is older than the JSP source file. Otherwise, if the servlet class exists, it is invoked if it is already loaded or it is loaded and invoked if it is not currently loaded.

Errors can occur during page compilation at three levels:

  1. The JSP tags themselves can be malformed. When using WebSphere Studio, the JSP validator will catch these errors and list them in the Tasks view when the JSP file is saved.

  2. The Java class generated during page compilation may produce Java compilation errors and will be reported as such. The JSP validator will catch most of the conditions that can lead up to these types of errors.

  3. The JSP can encounter runtime errors, just like any regular Java code. These errors are the most harmful in the user's eyes. If not handled properly ugly and cryptic stack dumps are displayed on the user's browser. These errors are best handled in an error page, which can clean up the original exception and display a meaningful error message to the user.


     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows