JSP Lifecycle

As has already been stated, JSPs go through a translation and compilation phase prior to processing their first request. This is illustrated in Figure 13.5.

Figure 13.5. JSP translation and processing phase.


The Web server automatically translates and compiles a JSP; you do not have to manually run any utility to do this. JSP translation and compilation can occur at any time prior to the JSP first being accessed. It is implementation dependent when this translation and compilation occurs but it is usually either

  • On deployment

  • When the first request for the JSP is received

If the latter strategy is used, not only is there a delay in processing the first request because the page is translated and compiled, but if the compilation fails, the client will be presented with some unintelligible error. If your server uses this strategy, ensure that you always force the translation and compilation of your JSP, either by making the first page request after it has been deployed or by forcing the page to be pre-compiled.

With J2EE RI, the translation and compilation only takes place when the page is first accessed. You can find the translated JSP in <J2EE installation> epository <machine name>web<context root>. You may find it useful to refer to the translated JSP to understand any compilation errors.

With J2EE RI, you can force the page to be pre-compiled by using your Web browser and appending ?jsp_precompile=true to the JSP's URL string. To pre-compile the date.jsp example, you could use the following:

http://localhost:8000/simple/date?jsp_precompile=true

Because the compiled servlet is not executed, there are several advantages:

  • There is no need to add any page-specific parameters to the URL.

  • Pages do not have to be compiled in an order determined by the application logic.

  • In a large application, less time is wasted traversing already compiled pages to find non-compiled ones, and it is easier to ensure that pages are not missed.

Detecting and Correcting JSP Errors

Realistically, you are going to make errors when writing JSPs. These errors can be quite difficult to comprehend because of the way they are detected and reported. There are three categories of error:

  • JSP translation

  • Servlet compilation

  • HTML presentation

The first two categories of error are detected by the Web server and sent back to the client browser instead of the requested page. The last type of error (HTML) is detected by the Web browser.

Correcting each category of error requires a different technique and is discussed in this section.

Translation Errors

If you mistype the JSP tags or fail to use the correct attributes for the tags, you will get a translation error returned to your browser. With the simple date example, missing the closing % sign from the JSP expression, as in the following code

Today's date is <%= new java.util.Date() >

will generate a translation error. Figure 13.6 shows the date JSP page with a translation error.

Figure 13.6. Browser showing JSP translation error.


Using the Web browser to report errors is an expedient solution to the problem of reporting errors, but this approach is not used by all Web servers. Some simply write the error to a log file and return an HTTP error to the browser. The JSP specification simply requires the Web server to report an HTTP 500 problem if there is an error on the JSP.

The error in Figure 13.6 shows a parse error defining an unterminated “<%= tag” on line 8 of the “date.jsp” page. The first line of the error is

org.apache.jasper.compiler.ParseException: /date.jsp(8,0) Unterminated <%= tag

This shows all of the useful information for determining the error. The first part of the line tells you the exception that occurred:

org.apache.jasper.compiler.ParseException:

In this case, a generic parsing exception reported by the JSP translator. The J2EE RI includes a version of the Apache Tomcat Web server and it is the Jasper parser of Tomcat that has reported the error.

The second part of the error identifies the JSP page:

/date.jsp

and the third part specifies the line and column number:

(8,0)

You know that the error is on line 8 of the date.jsp page. The column number is often misleading and is best ignored when looking for the error.

The final part of the error message is a brief description of the problem:

Unterminated <%= tag

The rest of the error information returned to the Web browser is a stack trace of where the exception occurred in the Jasper translator. This is of no practical use to you and can be ignored.

From the error information you should be able to identify the problem on the original JSP. Depending on the nature of the error, you may need to look at JSP lines prior to the one with the reported error. Sometimes errors are not reported until much later in the JSP. The worst scenario is when the error is reported on the very last line because this means the error could be practically anywhere in the JSP.

Compilation Errors

Compilation errors can occur when you mistype the Java code in a Java scripting element or when you omit necessary page directives, such as import package lists (see the next section).

Compilation errors are shown on the page returned to the browser and show the line number in error in the generated file. Figure 13.7 shows compilation error that occurs if you mistype Date as Datex in the date example show in Listing 13.3. The following is the error line:

Today's date is <%= new java.util.Datex() %>

Figure 13.7. Browser showing JSP compilation error.


The information provided identifies the line in error in the JSP file and the corresponding line in error in the generated Java file. If you cannot determine the error from the JSP file, you will need to examine the generated file.

As stated earlier, the J2EE RI saves the generated Java file in the repository directory in the J2EE installation directory. The actual location is in a directory hierarchy named after the current workstation, the application name, and the Web application name. The filename is generated from the original JSP name.

In the example error, if the current host is ABC123, the file will be stored as

<J2EE home>
epositoryABC123websimple002fdate_jsp.java

The following code fragment shows the generated code containing the Java error:

application = pageContext.getServletContext();
            config = pageContext.getServletConfig();
            session = pageContext.getSession();
            out = pageContext.getOut();

            // HTML // begin [file="/date.jsp";from=(0,0);to=(4,20)]
out.write( "<HTML>
<TITLE>JSP Date Example</TITLE>
<BODY>
  <BIG>
    Today's
date is ");

            // end
            // begin [file="/date.jsp";from=(4,23);to=(4,46)]
                out.print( new java.util.Datex() );
            // end
            // HTML // begin [file="/date.jsp";from=(4,48);to=(8,0)]
                out.write("
  </BIG>
</BODY>
</HTML>
");

            // end

As you can see, comments are inserted into the generated code to tie the Java code back to the original JSP code.

HTML Presentation Errors

The last category of error you can make with a JSP is to incorrectly define the HTML elements. These errors must be solved by looking at the HTML returned to the browser; most browsers have a menu option to let you view the HTML source for the page. After the HTML error is identified, you will have to relate this back to the original JSP file. Adding HTML comments to the JSP file can help you identify the location of the error if it is not readily apparent.

If no HTML data is returned to the browser, you have a serious problem with the JSP that is causing the generated servlet to fail without writing any data. You will need to examine your Web page very carefully for logic errors in the JSP elements; complex scriptlets are the most likely cause of the problem.

Your first step with a JSP that doesn't return HTML is to remove all of the JSP elements, leaving a plain HTML page, and ensure this is correctly returned to the browser. Gradually re-introduce JSP elements one at a time until the error reappears. Now you can correct the problem when you have identified where it occurs on the page.

Often, you will find that an HTML page is only partially complete. This usually indicates that the Java code has generated an exception part way through the Web page. Some Web servers (such as J2EE RI) will include the exception and a stack trace at the end of the incomplete page, others will write the error to a log file.

The JSP specification supports the concept of an error page that can be used to catch JSP exceptions, and this is discussed in more detail in the later sections on “The page Directive” and “Error Page Definition.” Very briefly, an error page is displayed instead of the JSP when the JSP throws an exception. An error page can be a servlet, a JSP, or an HTML page. It is usual to define an error page containing debugging information during development and replace this with a “user friendly” version on a live system. The “Error Page Definition” section later in this chapter shows how to write a simple debugging error page for use during JSP development.

JSP Lifecycle Methods

The JSP equivalent of the servlet init() method is called jspInit() and can be defined to set up the JSP page. If present, jspInit() will be called by the server prior to the first request. Similarly, a method called jspDestroy() can be defined to deallocate resources used in the JSP page. The jspDestroy() method will be called when the page is taken out of service.

These methods must be defined inside a JSP declaration, as shown in the following:

<%!
  public void jspInit() {
    ...
  }
  public void jspDestroy() {
    ...
  }
%>

One of the problems with these lifecycle methods is that they are often used to initialize instance variables. Because JSPs are really servlets, the use of instance variables can cause problems with the multi-threading mechanisms used by the Web server for handling multiple page requests. If an instance variable is accessed concurrently from different threads, inconsistent values for the data may be obtained, leading to inconsistent behavior of the code. This is a well known problem that occurs in any multi-threaded Java program and is not confined to servlets.

Access to shared resources (like instance variables) on a JSP should be thread safe. Either all access to shared resources should be protected by synchronized blocks of code, or the page should implement the SingleThreadModel interface that forces the Web server to only run a single thread at a time on each servlet (as discussed on Day 12, “Servlets”).

Because the servlet class is generated from your JSP code, you cannot implement the SingleThreadModel interface without support from the page translator. To specify translation requirements that affect the generated Java code for your Web page, you must add JSP directives to the page.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.221.144