Appendix B. Introduction to JSP and How Things Work

CONTENTS

IN THIS APPENDIX

  •  JSP Basics
  •  JSP Actions, Directives, and Implicit Objects
  •  A More Robust JSP Example
  •  Additional Information About JSP
  •  Summary

The goal of this appendix is to introduce JSP. Through examples, we will cover the basics of JSP. The goal is not to cover everything about JSP, but rather to give a new programmer enough knowledge to begin using JSP productively. We expect that you already have some basic Java and HTML knowledge.

JSP Basics

JSP is a simple Java-based specification for building dynamic Web sites. As an extension of Java servlets, JSP was designed to simplify the use of servlets. As a result, JSP is optimized to produce character-based output to a client, typically a person using a Web browser.

A new JSP developer needs to know six facts about servlets.

  1. JSP is only designed to perform character-based output. When a JSP page becomes a servlet, that servlet is also built to send character-based output. Since XML is 100% character based, we have no need to do binary operations for this book.

  2. All JSP pages are automatically compiled into a servlet by the JSP container. As a JSP programmer, the only required knowledge is the JSP code, because the container will take care of the rest.

  3. Since JSP is built on top of servlets, the documentation for some of the JSP objects can be found within the servlet documentation. We will indicate when this is the case.

  4. One reason JSP programmers eventually write servlets as they get more experienced is that servlets provide the ability to perform filtering on a request and response. Filtering is the ability to add a processing step either before or after the requested resource. For example, we could have our JSP pages output XML only, and have a filter that would apply an XSL stylesheet to that generated XML. The results would then be sent to the requesting client. Filters are part of the Servlet 2.3 specification.

  5. Another reason JSP programmers will want to write servlets comes from the use of listeners. A listener is a way to add JSP events to your Java objects. This means that the JSP container can notify your object of events such as when the application starts or ends, or when a user logs on, or one of a few other predefined JSP events. As an example, it is possible to build a listener that is triggered when a JSP application first starts up. Upon startup, an object could create and read initialization XML files for the application. Listeners are part of the Servlet 2.3 specification.

  6. Advanced JSP programmers tend to use servlets for nonvisual processing. An example of this would be a controller page. These pages never display a result, but rather redirect traffic to other JSP pages. JSP pages can still be used to perform nonvisual processing; servlets are just a little more robust for this task.

Several chapters of this book explore servlets. In Chapter 7, "Successfully Using JSP and XML in an Application," we build a listener to import an XML initialization file when the application starts. In Chapter 10, "Using XSL/JSP in Web Site Design," we write a servlet to process XML files generically. Finally, in Chapter 15, "Advanced Application Design," we show how to build a security filter. Keep in mind, it is possible that a JSP programmer will never need to directly program a servlet. However, more commonly, as JSP developers get more experienced in JSP, they will learn a few basic tricks with servlets to expand their JSP applications.

Let's look at how JSP works. The best way to do this is by building an example.

JSP Banner Example

JSP lets us use server-side processing to create client-side output. Typically, the output is an HTML page mixed with some client-side JavaScript. You can use and implement JSP pages in many different ways.

As an example, we build a simple text banner rotator (see Listing B.1). This text banner example is modified throughout the book as follows:

  • This first example is built purely as a JSP page.

  • We make the code reusable by implementing an include file and a JavaBean.

  • In Chapter 1, "Integrating JSP and Data," we introduce databases and then show how to access banner information stored in a database.

  • In Chapter 5, "Using DOM," we revise the example to work from an XML file.

  • In Chapter 7, "Successfully Using JSP and XML in an Application," we create a fully integrated example using XML and a database to store and access the banner data.

  • In Chapter 8, "Integrating JSP and Web Services," we make the example into a Web service.

  • Finally, in Appendix C,"Tag Library," we show how to build the text banner as a tag library.

Save the file into Tomcat as webapps/xmlbook/jspappendix/SimpleBanner.jsp.

Listing B.1 SimpleBanner.jsp; Inline Java Code Logic
<%@page contentType="text/html" %> <html> <head><title>Simple Text Banner Example One</title></head> <body> A very basic JSP page <div align="center"> <%@page import = "java.util.Random" %> <% String ls_Banners[] = {"Mars","Neptune","Saturn","Jupiter"} ; Random l_choose     = new Random(); out.print(" Visit " + ls_Banners[l_choose.nextInt(4)] ); %> </div> </body> </html>

When we run this page, we will see something similar to Figure B.1. (The planet name may be different due to the randomizing that occurs in the code. )

Figure B.1. Running SimpleBanner.jsp.

graphics/bfig01.gif

Let's begin by going over what is happening to the JSP page. Remember that a JSP page is just server-side code. This code produces the output that is seen by the client. The JSP page appears to be an HTML page with Java code embedded within the page. The JSP page in Listing B.1 is merely a template. Remember, the JSP template is used by the JSP container to build a servlet, and a servlet is a Java class file.

From this perspective, JSP can be considered an easy way to program servlets. Why not use servlets directly? The reason is that JSP is much easier to use and JSP templates retain the majority of the power of servlets. JSP offers a tremendous gain in productivity by offering an easy programming interface to servlets.

Think of a JSP page as a process. The first step in that process is telling the JSP container how we want our page to be set up. This is done through the JSP directives. The JSP directives are a way in which the JSP programmer sends messages to the JSP container about the page in which the directive resides. Directives use the format

<%@directive name %>

The text directive name is replaced with information. A directive produces no output, but rather passes information to the JSP container about how the servlet should be built. In our example page we have only one directive, the page directive, which looks like this:

<%@page contentType="text/html" %>

In this case, the page directive is informing the JSP container that this page will be of output type text/html. A few of the more common activities the page directive performs are

  • declaring the Java import statements (for example, <%@page import = "java.util.Random" %>)

  • setting up page buffering of the output (for example, <%@page buffer = "16kb" %>)

  • setting up error handling (for example, <%@page errorPage="SiteErrorPage.jsp" %>)

The next part of the process to think about is the HTML tags found in the JSP page. What happens to those tags and text? Looking at our sample page, we can't help but notice that the page looks more like an HTML page than a Java class. (Remember that servlets are Java classes.) The JSP container takes all the HTML and text statements and writes them into the output buffer for us. In Listing B.1 we have the following statement:

<html>

But the actual code generated looks like this:

out.write("<html>\r\n");

All text-based code is generated into write statements. How do we tell the JSP container what is Java code and what is text? This is done by using scriptlets to indicate where our Java code resides. A scriptlet looks like this:

<% Your code %>

Any code contained within the delimiters <% %> is sent straight into the servlet to be executed as Java code.

Let's look at another part of Listing B.1:

<% String ls_Banners[] = {"Mars","Neptune","Saturn","Jupiter"} ; Random l_choose     = new Random(); out.print(" Visit " + ls_Banners[l_choose.nextInt(4)] ); %>

These lines are executed as Java code. In this case, the code just randomly chooses a String to display. At this point, you might stop and wonder about out. If this is Java, where is the out class defined? JSP provides several objects for us to use. These objects are called the implicit objects and are always available to use in any JSP page. The out implicit object lets us write data to the output stream that goes to the client. In this case, we are printing out the result of the banner string.

Clearly, there is a lot of processing involved in turning the JSP page into a servlet. The nice thing about JSP is that it permits us to use the familiar HTML-style format and mix in our Java code to suit our needs.

Actions

Our earlier simple example covered quite a few JSP basics, but we missed one that needs mentioning at this point: JSP actions. In the last example, we showed how to use scriptlets to indicate where the Java code resides. It turns out that JSP prepackages some ready-to-use Java code for us. These prepackaged code elements are called actions. Actions are always written as XML tags and have the following format:

<jsp:actionname> </jsp:actionname>

An example of an action is <jsp:useBean>. This particular action lets us call and create a JavaBean to use on a JSP page. JSP has a few prebuilt actions that will be covered in the next section. The neat thing about actions is that JSP enables us to build our own.

A custom action is also officially known as a JSP tag library. The fact is, by letting us build our own actions, JSP permits us an avenue of unlimited expansion to make efficiently programmed Web applications.

JSP Actions, Directives, and Implicit Objects

This section will cover a few of the common elements and objects used within JSP. Table B.1 shows the standard JSP and JSP XML tag formats of these elements. Table B.2 describes the elements. You might call these pieces the heart of JSP (with design concepts being the soul).

Table B.1. Format of JSP Elements
JSP Element Standard JSP Format JSP XML Tag Format
JSP comment <%-- Your Comment --%> N/A
Declaration <%! Code %> <jsp:declaration>
Expression <%= a Java expression %> <jsp:expression>
Forward <%jsp:forward page="relative URL" /> same as standard JSP
Include action <jsp:include page="relative URL" same as standard JSP flush="boolean"/>
Include directive <%@include file="RelativeURL"%> <jsp:directive.include file=""/>
Page directive <%@page %> <jsp:directive.page />
PlugIn action <jsp:plugin><jsp:plugin> same as standard JSP
Tag library directive <%@taglib uri="" prefix="" %> N/A; called in root
UseBean action <jsp:useBean /> same as standard JSP

 

Table B.2. JSP Element Descriptions
JSP Element Description
JSP comment Anything within a JSP comment only resides within the JSP page. Everything within the JSP comment is stripped out before the JSP page is created.
Declaration Declarations are the source of more problems than almost anything in JSP. A declaration may be used to define methods and variables. However, declarations are created within the JSP servlets class body. This means that for all practical purposes a declaration creates a class variable or method that is available across all active instances of a JSP page. If misused, this may in turn create threading and timing problems. We rarely use declarations in this book. This "bad boy" element is mentioned here as a warning to newer JSP developers. Until you understand all the implications of a declaration, do not use it.
Expression An expression is effectively a shortcut for the out.print function. Note that a semicolon (;) is not used at the end of the expression. In addition, a JSP expression will automatically convert data results to a String. This means that any result of the expression that cannot be formatted as a String will cause an error to occur.
Forward The forward command transfers the request of the current JSP page to a new JSP page.
Include action This action imports a file into a JSP page. The action is processed while the page is executed after a user request of the page. Since this is processed during the request, JSP statements within the include action are evaluated at runtime rather than at compile time. The disadvantage is that the include action is much slower than the include directive because all the processing happens every time the page is requested by a user.
Include directive This directive imports a file into the JSP page at the location of the directive. The include file is placed inline before the page is compiled into the servlet. Since this file is processed before the JSP page's servlet is created, it isn't possible to dynamically modify the include directive.
Page directive This directive defines attributes that affect the processing of the JSP page. These attributes define properties of the JSP page itself.
PlugIn action This action executes an applet or JavaBean within the JSP page.
Tag library directive This directive creates a tag library definition for a JSP page to use. It also tells the JSP container which tag library mapping to use relative to the tag library instance called by the JSP page.
UseBean action This action creates an instance of a JavaBean to be used within a JSP page.

The next important pieces within JSP are the implicit objects (listed and described in Table B.3). These objects are always available to any JSP page. They provide access to the entire JSP application environment and are critical in the day-to-day operations of any JSP page.

Table B.3. JSP Implicit Objects
Implicit Object Description
application

The application implicit object gives access to data and objects, which are stored at a global level of your Web site. A JSP page can also use this object to communicate back to the JSP container. Each Web application within a JSP container has its own application object.

This object is based on the javax.servlet.ServletContext class. This class is part of the Servlet specification.

config

This object is used by the servlet container to send information to a servlet during the servlet's initialization. This object isn't used very often by JSP developers.

This object is based on the javax.servlet.ServletConfig class. This class is part of the Servlet specification.

exception

This object is used to transfer error messages to a JSP error page. JSP permits us to build specialized error pages to catch errors from any JSP page. The exception object contains the error from a JSP page that has JSP error handling turned on.

This object is based on the javax.Lang.Throwable class.

out

This object is used to access the JSP output stream. This typically means using the print function to write data and text to the client.

This object is based on the javax.servlet.jsp.JspWriter class.

page

This object is the instance of the current JSP page class. From a Java point of view, page translates into this.

This object is based on the javax.lang.Object class.

pageContext

This is a very important object used for JSP pages. It is not commonly used by new JSP programmers, but is used often when building tag libraries. This object contains a reference to all the implicit objects that are listed. It is through this object that tag libraries have access to the JSP page that uses them. Tag libraries can only access the implicit objects using this object.

This object is based on the javax.servlet.jsp.PageContext class.

request

The request object is used to gather information about the client request for the JSP page. This object is used to query the post and get values sent within the HTTP request.

This object is based on the javax.servlet.ServletRequest class. This class is part of the Servlet specification.

response

This object has methods to aid in sending output to the client. It is not used very often by JSP programmers, as out is the object to use for directly communicating with the client.

This object is based on the javax.servlet.ServletResponse class. This class is part of the Servlet specification.

session

The session object is extremely important within JSP. It provides a way to track information for the duration of a visitor's stay at a JSP application. The session permits us to track users as they use a JSP application.

This object is based on the javax.servlet.http.HttpSession class. This class is part of the Servlet specification.

The implicit objects you will get to know extremely well over time are application, out, session, request, and pageContext.

Now that we have quickly reviewed the objects and elements of JSP, let's jump to our next example.

A More Robust JSP Example

The first example was limited, as it only ran on a single page. Let's expand the example a bit and make the code slightly more robust. To do so, we will add the following features to our example:

  • Instead of using an array to store the data, we will build a special Java class to store it.

  • We will store banner information in the application object, so any page can access the same data.

  • We will build an include file that any page can use to display the banner.

Once all of these features are created, we will combine and use them in a separate page to show how it all comes together. Let's start off by building a JavaBean that is a class with the sole purpose of storing banner ad data, as shown in Listing B.2. Save this example as webapps/xmlbook/WEB-INF/classes/xmlbook/jspappendix/BannerAd.java.

Listing B.2 BannerAd.java; Using a Bean for Logic
package xmlbook.jspappendix; import java.beans.*; public class BannerAd extends Object implements java.io.Serializable {     private String name     = "undefined";     private String link     = "undefined";     private String linkText = "undefined";     public BannerAd() {}     public BannerAd(String as_name, String as_link, String as_text)     {setName (as_name) ;      setLink (as_link) ;      setLinkText (as_text) ;     }     public String getName ()     {   return name;   }     public String getLink ()     {   return link;   }     public String getLinkText ()     {   return linkText;   }     public void setName (String as_data)     {   name = as_data;    }     public void setLink (String as_data)     {   link = as_data;    }     public void setLinkText (String as_data)     {   linkText = as_data;    } }

The whole purpose of the code just built is to take in the banner data and store it within the object. The data is stored within the private variables:

private String name     = "undefined";

The actual data is set and accessed through public methods:

public String getName () {   return name;   } public void setName (String as_data) {   name = as_data;    }

The object also has a convenience constructor method, which will set all the properties at once:

public BannerAd(String as_name, String as_link, String as_text)

Once we create a BannerAd object, we can save the object and retrieve the data easily with the methods within the class.

Once you've written this code, compile it. Also, don't forget to stop and restart Tomcat. This is to permit Tomcat to find and register the newly created class file. In this example, notice that we are saving the Java and class files in the WEB-INF/classes directory. By placing our files in this directory, we enable Tomcat to find and use the class files automatically for this particular Web application. While we could store the files anywhere, doing so would necessitate manually modifying the classpath that Tomcat uses to include our classes. Quite honestly, it's simpler to place them in the WEB-INF/classes directory and let Tomcat deal with the classpath.

Keep in mind, sometimes Java classes will be built that may be used in more than one Web application. When this is the case, it is better to package your classes into a JAR file (a compressed file that Java can extract automatically). Once you have a JAR file, it becomes easy to deploy it to the WEB-INF/lib directory of any Web application. When all the Web applications need to see some classes, move the JAR files to the root Tomcat lib directory so that all the Web applications executing on that server will have access to them.

This object happens to also be a simple JavaBean. A JavaBean is a Java object that implements the Serializable class and follows a few rules:

  • The object must have a constructor with no arguments.

  • Any property is exposed with a setter and getter method.

  • Getter methods are in the form getXYX, where XYX is the first-letter capitalized name of the variable. In our example, the linkText property has a getter method of getLinkText. The setter methods follow the same rules as the getter methods.

Generally, within a JSP project it's a good idea to place any reusable logic into a JavaBean. The fact that the code is within a reusable package makes Web applications easier to maintain, expand, and document. You might be wondering about JSP tag libraries at this point. Shouldn't we put reusable code in a tag library? The answer is yes, but with the understanding that the tag library built should also use JavaBeans for any of its reusable logic. The only code placed within the actual tag library will be JSP-specific interfacing code. All reusable business logic should still be in a JavaBean.

Let's briefly mention one advantage of using JavaBeans: documentation. Most experienced programmers agree that documenting a JSP project is a hassle. For example, the Java JavaDoc methodology cannot be used to document a JSP page. The good news is that JavaDoc can be used to document your JavaBeans. If you are using NetBeans, check out the JavaDoc support that is built into the editor. It is a nice feature worth using.

Next, let's build a JSP page to store the banner values in the BannerAd JavaBean built in Listing B.2. Once data is place within the JavaBean, the code will push the JavaBean into memory so that any of our JSP pages can access the data.

This next example, shown in Listing B.3, will be saved as webapps/xmlbook/jspappendix/BannerStore.jsp.

Listing B.3 BannerStore.jsp; JSP Page Using Bean
<%@page contentType="text/html"         import="xmlbook.jspappendix.*"%> <% BannerAd banners[] = new BannerAd[4]; banners[0] = new BannerAd("Sun","http://www.sun.com","The Home of Java"); banners[1] = new BannerAd("JSPInsider","http://www.JSPInsider.com","JSP News"); banners[2] = new BannerAd("SAMS","http://www.samspublishing.com","Java books"); banners[3] = new BannerAd("Jakarta","http://jakarta.apache.org/","Kewl Tools"); application.setAttribute("sitebanners",banners); %> <html> <head><title>JSP Page</title></head> <body> Validating the data stored in the application object.<br/> Banners placed in the application space were:<br/><br/> <% BannerAd[] testvalues =(BannerAd[]) application.getAttribute("sitebanners");     for (int i = 0; i < testvalues.length ; i ++)     {  out.print("<br/>" + testvalues[i].getName()); } %> </body> </html>

The code is brief. It creates an array of BannerAd objects and initializes each element of the array with the data to represent a banner:

BannerAd banners[] = new BannerAd[4]; banners[0] = new BannerAd("Sun","http://www.sun.com","The Home of Java"); banners[1] = new BannerAd("JSPInsider","http://www.JSPInsider.com","JSP News"); banners[2] = new BannerAd("SAMS","http://www.samspublishing.com","Java books"); banners[3] = new BannerAd("Jakarta","http://jakarta.apache.org/","Kewl Tools");

Once the banners are created, the JSP page takes the array of BannerAd objects and stores it in the JSP application object:

application.setAttribute("sitebanners",banners);

In this case, the code creates an application attribute called sitebanners that contains an array of BannerAd.

Once in the application object, any other JSP page within the same Web application can access this data.

As a quick example, this page pulls the data back out of the application space to show that it is indeed stored properly:

<% BannerAd[] testvalues =(BannerAd[]) application.getAttribute("sitebanners");     for (int i = 0; i < testvalues.length ; i ++)     {  out.print("<br/>" + testvalues[i].getName()); } %>

Notice that when an attribute or object is stored in the application object, it's stored as a Java Object. This means that when the code retrieves the object, the object must be "typed" so that it can be returned to its original form:

BannerAd[] testvalues =(BannerAd[]) application.getAttribute("sitebanners");

Running the page created in Listing B.3 will produce the result shown in Figure B.2. (If NetBeans is the IDE you've chosen to use, make sure to mount the class directory above which the Bean is located. This will clear up any errors that may have occurred in compiling the class within NetBeans.)

Figure B.2. Running BannerStore.jsp from Listing B.3.

graphics/bfig02.gif

The next step is to build an include file. This file will re-access the data that is stored in the application space.

An include file is a file that can be reused from JSP page to JSP page. The actual file to be included is inserted at the spot of the include request within the JSP page asking for the file.

We will choose the include directive because it is faster and we don't need the extra flexibility of the include action.

Save Listing B.4 as webapps/xmlbook/jspappendix/inc_banner1.jsp.

Listing B.4 inc_banner1.jsp; Logic in Include File
<div align="center"> <%@page import = "java.util.Random,                   xmlbook.jspappendix.*"%> <% BannerAd[] testvalues =(BannerAd[]) application.getAttribute("sitebanners");     if (testvalues != null)     {         Random l_choose = new Random();         int li_selection = l_choose.nextInt(testvalues.length);         out.print("<a href=\"" + testvalues[li_selection].getLink());         out.print("\">" + testvalues[li_selection].getLinkText() + "</a>");     }     else     {        out.print("<br/> No Banners are Stored in the Application. <br/>");        out.print("<br/> Execute BannerStore Page to Initialize the System. <br/>");     } %> </div>

Notice that this include file isn't a complete HTML document. Rather, it's a complete standalone piece of an HTML document. It begins and ends with a div tag so that it can stand alone as well-formed HTML. In reality, an include file can be any part of a legitimate XML, HTML, or JSP document. Likewise, the code within the file should have no dependencies on code within the host page it's included within. It's a good idea to keep include files as atomic (simple and performing only a single function) as possible. This makes them easier to reuse from page to page. In addition, it makes them easier to maintain.

Imagine the maintenance nightmare that would result if the include file depended on logic or tags being present in each file that included it. Let's say the include file is part of an HTML table, and the file that includes it will build the remainder of the table. A bad include file might look like the following:

<td> Mydata 1 is <%= myvalue1 %> </td> <td> Mydata 2 is <%= myvalue2 %> </td> <td> Mydata 3 is <%= myvalue3 %> </td>

This is a terrible design because it depends on the file using the include file to create the table correctly. In addition, if we need to make any changes to the include file, each file that uses this include file might also have to be changed. This defeats the purpose and usefulness of an include file. Try to keep include files self-sufficient. While a JSP page can depend on an include file, the include file should never depend on the host page.

Generally, reusable code should be placed within tag libraries or JavaBeans. Tag libraries and JavaBeans have three advantages over include files:

  1. They are easier to move between projects.

  2. They are easier to document.

  3. They are easier to maintain.

However, include files are a venerable and accepted way to create reusable code. Most often they are used for building reusable header and footer blocks in a JSP project. With the inclusion of filters in JSP 1.2, we will probably see programmers replace include files with filters. However, old habits are hard to break, so include files will be around for a long time. Just keep in mind that more times than not, they aren't the best option. So now you may be asking, Why use an include file? They are easier to build and faster to implement. So an include file might be great to use in building a quick prototype system. Keep in mind that there are usually several different ways to do almost anything within JSP, but the final choice comes down to what tradeoffs you are willing to make for your implementation choice.

With all this in mind, let's build a page that uses our include file. Listing B.5 shows the code to enter. This page should be saved as webapps/xmlbook/jspappendix/BannerPageInclude.jsp.

Listing B.5 BannerPageInclude.jsp; JSP Using an Include File
<%@page contentType="text/html" %> <html> <head><title>Using an Include File</title></head> <body> A little more complicated JSP Page. <%@ include file="inc_banner1.jsp" %> <%--     <p><b> This line wont show in the final HTML </b></p>     <!-- HTML comment -->     <%     /*just a brief mention on commenting */     out.print(" this wont show due to the JSP comments!");     %> --%> </body> </html>

Running this page produces the output shown in Figure B.3.

Figure B.3. Using an include file.

graphics/bfig03.gif

This example shows that the included file was indeed incorporated into the final page, generating a banner for us. Since the final page was so simple, we added an extra bit about using comments within a JSP page.

JSP allows comments to be expressed in the primary language of the page. Since most people use Java, you can use the standard Java coding comments that look like this:

<% // your comment /* your comment */ %>

Notice that the Java comments happen within the scriptlet. To comment HTML or XML, use the standard HTML comment:

<!-- comment here -->

However, JSP also adds a special comment known as the JSP comment to the mix. A JSP comment takes the following form:

<%--  your comment --%>

JSP comments are special. Anything within the JSP comment is excluded from the final servlet that gets generated by the JSP container. This means that not only are code and statements within a JSP comment not executed, they also are never sent down to the client. Java comments also aren't sent to the client, but do exist in the servlet created for the JSP page. JSP comments provide a great way to comment out testing code and code you are trying to debug.

As an example, say you want to test to see whether a problem exists in the include file or the JSP page; we could quickly modify Listing B.5 by just commenting out the include file statement like this:

<%-- <%@ include file="inc_banner1.jsp" %> --%>

This will let the JSP page run without the include file. Try it and see what happens. The include file step will never happen at all! JSP comments provide a great way to strip out sections of code without actually removing the code.

Additional Information About JSP

This appendix has shown the basics of JSP. Now let's examine a few more JSP-related topics.

What Is JSP and How Does It Work?

JSP provides a layer of abstraction from servlets. JSP is built on servlets and is designed to make it easy for less experienced programmers to create efficient servlet design and composition.

When any client first requests a specific JSP page, it is compiled into a servlet. At this point, the servlet is compiled and executed. The results are then sent back to the client. Once a JSP page has been compiled, any further requests will use the precompiled version. It is also possible to precompile all JSP pages so that no user experiences a compiling delay. The method of precompiling will depend on the servlet container you implement.

The Web container is smart enough to compile a JSP page on a need-only basis. Usually, a JSP page request is handled directly by executing the servlet class that was created from it. Only when a JSP page has changed since the last request for it does the system go through the process of creating a new servlet from that JSP page.

Examine Figure B.4, which demonstrates the detailed life cycle of a JSP page. The diagram illustrates that while a JSP page appears to be a single step to the user, in reality several important things are happening in the background. The most important of these is that a JSP page is compiled into a servlet, as shown at step 3a in the figure.

Figure B.4. The life cycle of a JSP page.

graphics/bfig04.gif

Figure B.4 demonstrates JSP pages' ability to do advanced processing. Clearly, running a JSP page is a several-step process. It's this layering of steps that permits a great degree of freedom in the creation of the various aspects of Web application projects. Another interesting fact that Figure B.4 points out is the ability to handle and process any user-defined file extension, as shown in section C of the figure. This is important, as it will permit us to create our own special extensions.

For example, say you have the extension .rpt to create and process XML-based reports. Any requested JSP page ending in .rpt can be mapped to a process to handle these reports. We use this capability on the JSP Insider Web site. Whenever a page with a .xml extension is requested, Tomcat automatically applies XSL templates to convert the XML document into a standard HTML page to be sent to the client. We show you how to expand JSP to do this in Chapter 10.

JSP XML Syntax

JSP has two forms of syntax: original blend (standard syntax) and XML syntax. Starting with JSP 1.2, a JSP page can be written entirely as an XML document. This is a great feature as it means we can apply many of the techniques we will use in this book directly to a JSP page. If you are new to JSP, be aware that the standard syntax is still the prevalent style of code for a JSP page. Over time, this will change and programmers will use the XML syntax more often. A programmer cannot mix the two versions of syntax within a single JSP file. Strangely enough, though, an included JSP page does not have to use the same syntax as the JSP page that is including it.

Does either style have an advantage over the other? Unless there is some special XML processing on a page, it really doesn't make a difference from a processing point of view which style is used within a page. The advantages and disadvantages pertain to the human factor. The advantage of standard syntax is that most JSP developers are used to it already, and most of the documentation is written relative to it. In addition, the standard syntax is easier to hand-code. The disadvantage of the XML syntax is that it is a little more awkward for humans to handle. The advantage of XML syntax is that the JSP page becomes an XML document, which opens up the possibility of parsing the document and modifying it according to the rules of XML. This means that XML syntax is perfect for tools that generate JSP, or for programmatically building or modifying JSP files. We cover an example of this in Chapter 15.

JSP Documentation Resources

The best resources for JSP documentation come from the Sun Web site. All JSP developers should have access to the following resources:

  1. The JSP specification document explains how JSP works and is a great JSP reference document. The JSP 1.2 JavaDocs list all the methods and attributes that are available in JSP. Both documents can be found at http://java.sun.com/products/jsp/download.html.

  2. Likewise, a JSP developer should have access to the servlet specification document and the servlet JavaDocs. These documents can be found at http://java.sun.com/products/servlet/download.html.

  3. Finally, no single book or document will ever answer all questions. To aid in answering any question that arises, Sun has two excellent resources for developers. First, the Sun JSP forum can be found at http://forum.java.sun.com/forum.jsp?forum=45. Second, the JSP ListServ archive can be found at http://archives.java.sun.com/archives/jsp-interest.html. These forums are the best place to ask questions and look at others' answers regarding the use of JSP.

Added together, these resources will form the information foundation for any JSP developer.

Summary

In this appendix, we've reviewed some of the basics of JSP. While we haven't given you enough information to make you a full-fledged JSP programmer, we have covered enough basics to help start new programmers on the road to using JSP. Also at this point, you should have enough of an understanding of JSP to use the rest of the book.

CONTENTS


JSP and XML[c] Integrating XML and Web Services in Your JSP Application
JSP and XML[c] Integrating XML and Web Services in Your JSP Application
ISBN: 672323540
EAN: N/A
Year: 2005
Pages: 26

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net