subsection contents

Technology Investigation Outline - JavaServer Pages


The purpose of this document is to explore the capabilities of JavaServer Pages (JSPs) in the context of developing web-based applications.

The document provides a broad overview of standard JSP technology, including:

  1. Broad overview of JSP operation
  2. Development steps for a form
  3. Description of alternate JSP-based application models (i.e. Model I and Model II)
  4. Consideration of object frameworks based on JSP
  5. Other issues

A list of related online resources is provided at the end of the document.


What is a JavaServer Page?

A JavaServer page is a page created by the web developer that includes JSP technology-specific tags, declarations, and possibly scriptlets, in combination with other static (HTML or XML) tags. A JSP technology-based page has the extension .jsp; this signals to the web server that the JSP technology-enabled engine will process elements on this page.
Sun JavaServer Page FAQ

JSP technology is an extension of the Java Servlet API. In fact, JSPs are compiled into servlets and then executed just like any other servlets. In many respects JSPs are Sun's response to Microsoft's Active Server Pages (ASPs).

Being based on HTTP servlet technology, JSPs function within the request/response paradigm. More information about this paradigm is presented in the Technology Investigation Outline of Servlets.

In order to make use of JSP, a web server or application server needs to have appropriate JSP and servlet engines (or modules) installed. For example, Apache web server requires JServ for executing servlets, and an additional component such as GnuJSP to handle JSP translation. Some vendors provide an all-in-one web server. Oracle 8i delivers all this functionality straight from the database server.

JSPs offer several benefits in the development of dynamic web content:

  • Separation of content generation from presentation
  • Emphasis on reusable components
  • Simplification of page development with minimal set of tags, rather than complex scripting language

The third benefit is open to question, as the subsequent example will show. It is possible for developers to embed rather complex Java code directly into the JSP, making it difficult for a web developer with limited Java skills to maintain the page.

The separation of content generation from presentation is a real improvement of JSP technology over standard Java Servlets. Typically servlets directly encode both the HTML markup for presenting information and the dynamic content created by the application or business logic. This means that any change in the presentation of a web page, for either technical or aesthetic reasons, requires the Java developers to modify the HTML generation portions of the servlets. The servlets will have to be recompiled and retested. This cycle may be repeated until the desired effect is achieved, leading to increased maintenance costs.

When implemented properly, JSPs can overcome this problem by confining static presentation logic within the .jsp file and having the business logic on the server (typically in a JavaBean).

Another benefit of JSPs is that they allow for separation of duties within a team. Graphic designers and other producers of web content have greater control of the presentation and can use standard HTML tools such as Macromedia Dreamweaver and Adobe GoLive. All that page designers need do is to learn a small set of special JSP tags which can be used to provide the dynamic content. Java developers are also liberated from the burden of having to generate complex HTML markup from within their code. They can instead focus on solving the actual business problem.


How JavaServer Pages Work

A JavaServer page looks like a standard HTML or XML page, with additional elements that the JSP engine processes and then removes from the generated page. An example JSP will be presented and described in the next section.

There are several JSP-specific extensions to standard HTML, including:

  • Comments
  • Directives
  • Declarations
  • Scriptlets
  • Expressions
  • JavaBean-related tags

A JSP comment allows developers to document parts of a page. These comments will not be visible in the generated page. Comments are enclosed in <%-- and --%> markers.

A directive passes information to the JSP engine, enabling modification of certain characteristics of the JSP and the generated servlet. Example directives include the naming of methods, identifying packages to be imported and which interfaces will be implemented. Directives are enclosed in <%@ and %> markers.

A declaration identifies class-wide variables and methods used by the generated servlet. Declarations are enclosed in <%! and %> markers.

An expression contains a Java expression whose value will be evaluated and inserted into the generated page. Expressions are enclosed in <%= and %> markers.

A scriptlet is usually a small script that performs functions not supported by tags or ties everything together. Java is the native scripting language for JSP 1.0 software. Scriptlets are enclosed in <% and %> markers. There are several predefined variables that will be accessible within the generated servlet. For example:

The JavaBean-related tags allow access to any Java object from within a JSP. This mechanism facilitates the separation of presentation and business logic. It is arguably the most important feature of JSP technology.

The following example tag shows how to access a JavaBean within a JSP:

<jsp:useBean id='instanceName' scope='scopeType' class='packageName.className' type='packageName.className'/>

This tag will instantiate a bean of the class 'packageName.className' and assign it the id 'instanceName'. This id can be used to reference the instance within the JSP. The scope of the bean can be one of the following: page, session, request or application.

Once a bean instance has been created, a page can interact with the bean's properties using the following tags:

  • <jsp:setProperty name='instanceName' property='propertyName' value='propertyValue'/>
  • <jsp:getProperty name='instanceName' property='propertyName'/>

These tags invoke methods defined in the bean as setPropertyName() and getPropertyName(), respectively. Developers should follow the standard JavaBean naming conventions for variables and methods to ensure that beans can be used effectively.

The appendices contain examples which demonstrate how JavaBeans can be used to encapsulate business logic.

Another JSP extension to HTML is the ability to create customised tag libraries. These libraries allows developers to wrap powerful functionality inside a tag architecture that is readily accessible to web page designers and the tools they use.

For a more detailed description of JSP syntax, consult Sun's online documentation. It should be noted that the JSP specification is still evolving and there exist alternative syntax rules for JSP components. For example, some rules are designed to be more suitable for use within documents written in Extensible Markup Language (XML).

When a client requests a JavaServer page, the web server invokes a special servlet called the PageCompileServlet. The PageCompileServlet is loaded and initialised like any other servlet. It compares the page to a list of cached pages. If the page is not in the cache (as in the case of a new request) the JSP is translated into source for a servlet class. JSP-specific tags will be recast as Java statements. All other standard HTML markup will be rewritten as a series of println() calls to the PrintWriter object associated with the generated servlet.

PageCompileServlet then compiles the servlet class, loads the servlet, then invokes the service() method of the servlet. The list of cached pages is updated to include the new servlet. Subsequent requests for the page will be passed onto the relevant servlet's service() method.

Obviously there is an overhead associated with the first invocation of a JSP. However JSPs still have an advantage over traditional CGI applications in that they do not require a new process to be spawned to handle each and every request.

Some web servers provide the option of precompiling JSPs, thereby eliminating the translation step with initial invocations.

Another desirable feature of JSP engines is the detection of any changes to the source of JSPs. Modified JSPs should be translated into new servlet classes and recompiled.


Developing a Form Using JavaServer Pages

To demonstrate how to develop a form using JSP technology, the following example JSP will be discussed. It's a rather simple JSP that prompts the user to enter a string, which is then encoded into a format that is URL-friendly.

A couple of points should be made regarding this example. Firstly, it has been coded in such a way as to show several JSP-specific tags. Secondly, it demonstrates how easy, and messy, it is to mix Java code and HTML markup within JSPs.

A "cleaner" example which makes use of server-side JavaBean will be provided in appendix 2.


     1       <!--
     2    -- Sample JavaServer Page
     3    -- Name: URLEncodingServerPage.jsp
     4    -- Purpose: Present user with a form for entering a single string.
     5    --          When form is submitted, contents of string are encoded as URL,
     6    --          which is then returned to the user.
     7    -- @author: brunoa
     8    -- Date created:  11 April 2000 14:30
     9    -- Last modified: 12 April 2000 15:45
    10    -->
    11  <HTML>
    12  <HEAD><TITLE>URLEncodingServerPage Output</TITLE></HEAD>
    13  <BODY BGCOLOR="gainsboro">
    14  <%@ page language="java" import="*, java.util.*" %>
    15  <%
    16    String inputString = request.getParameter("input_string");
    17    if (inputString != null)
    18    {
    19    // display the results of form processing
    20  %>
    21  <H2>URLEncodingServerPage Output</H2>
    22  <P>Input string: <%= inputString %></P>
    23  <P>URL Encoded: <%= URLEncoder.encode(inputString) %></P>
    24  <P>&nbsp;</P>
    25  <HR>
    26  <%
    27    }
    28    else
    29    {
    30       // initialise string as blank
    31       inputString = "";
    32    }
    33  %>
    34  <H2>URLEncodingServerPage Form</H2>
    35  <FORM NAME="URLEncoder" ACTION="URLEncodingServerPage.jsp" METHOD="POST">
    36  <P>String to encode: 
    37  <INPUT TYPE="TEXT" NAME="input_string" VALUE="<%= inputString %>" SIZE="60">
    38  </P>
    39  <INPUT TYPE="RESET">
    41  </FORM>
    42  <P>&nbsp;</P>
    43  <P><SMALL><I>Script: URLEncodingServerPage 0.1 by Bruno Andrighetto<BR>
    44  Date: <%= new Date() %></I></SMALL></P>
    45  </BODY>
    46  </HTML>


A line-by-line description will now be provided.

Lines 1 to 10 contain some comments regarding the page.

Lines 11 to 13 contain HTML markup to begin the page, set the title, and set the background colour.

Line 14 contains a JSP directive, declaring that Java will be used. Also, it ensures that, in addition to the standard servlet packages, the generated servlet will import additional packages:

  • package is required for providing the URL-encoding functionality
  • java.util package is required for displaying the date

Lines 15 to 20 contain a JSP scriptlet:

Line 16 creates a String object, inputString, and sets it to the value of the input_string parameter of the request object.

Line 17 tests inputString to see if it null.

Line 18 starts a new block to be executed if it is not null.

Lines 21 to 25 contain HTML markup for displaying the output of the form-processing:

Line 22 contains a JSP expression which inserts the value of inputString into the page.

Line 23 contains a JSP expression which uses the URLEncoder class to encode the inputString and inserts it into the page.

Lines 26 to 33 contain a JSP scriptlet:

Line 27 ends the block started at line 18.

Line 28 contains the else statement corresponding to the if statement in line 17.

Line 29 starts the contents of the else block.

Line 31 sets inputString to an empty string.

Line 32 ends the block started at line 29.

Lines 34 to 41 contain the HTML markup to display the form.

Lines 35 specifies the FORM tag. Note that the action attribute is set to the JSP processing the form (in this case, the same as the JSP displaying the form). Also, the form will be submitted using the POST method.

Line 37 contains a JSP expression which sets the value of the form's input_string field to inputString.

Lines 42 to 46 contain the HTML markup to complete the page.

Line 44 contains a JSP expression which uses the Date class to display the current date.


Note that by default, the JSP code will be compiled into the doPost() method of the generated servlet. There are JSP directives which allow programmers to override this and other defaults.

Also, as mentioned earlier, some packages are imported implicitly. Specifically:

  • javax.servlet.*
  • javax.servlet.http.*


Alternate Application Models using JavaServer Pages

A major consideration when designing any application is deciding how to breakdown the application into easily understood and maintainable components or subsystems. Web applications are no different to any other applications in this respect. Current thinking suggests that the Model-View-Controller paradigm is appropriate for Java-based systems.

An MVC implementation separates the model (or business logic) from the view logic in an application, with a controller managing the interaction between the model and the view. In the context of a Java-based web application, JavaBeans provide an obvious mechanism for implementing the business logic. As argued earlier, JSPs provide a workable means for implementing the view component. The question remains to decide where to put the controller.

Sun's JavaServer Page 0.92 specification defined two application models for delivering web applications based on JSP technology. In Access Model I a JSP also acts as the controller, whereas in Access Model II a servlet interacts between the JSP and the JavaBeans. The diagrams below show how these access models operate within the context of web applications.

Access Model I
Access Model I

Access Model II
Access Model II

Derived from: "Java Server Pages and Servlet Design", JavaReport4(12), Dec. 1999

While the latest JSP specification no longer refers to these two access models specifically, they are still relevant to the process of designing web applications.

Model I mixes controller logic and view logic into the same page. This is basically the approach used in the example discusses earlier, making it more difficult to maintain. However, such an implementation may require less code, and so may be more suitable for small applications or prototypes.

By keeping controller and view logic separate, applications based on Model II should be easier to maintain. Also, the work can be allocated between Java programmers and HTML developers, each being able to use purpose-built tools to do their jobs.


Developing Object Frameworks based on JavaServer Pages

The use of a purely JSP-based architecture is inappropriate for nontrivial web applications, since such an architecture fails to take advantage of the separation of presentation and business logic. Therefore, it is suggested that JSPs themselves contain most or all of the HTML markup, with a only dynamic content provided by backend components. It still may be beneficial to create a framework for generating basic HTML.

A framework can also be developed to provide an abstraction over database connectivity. Developing such a framework using JavaBeans may require a little more effort, but it will help achieve the goals of JSP: separation and reuse.


Other Relevant Issues

State, Authentication and Chunking

Since JavaServer Pages are an extension of Java Servlet technology, most features available to servlet programmers are inherited by JSPs. The standard request and response objects are instantiated and made available for use within JSPs. Standard session and cookie management capabilities can likewise be used within JSPs.


Since JavaServer pages will need to be compiled into servlets before being presented, there will be a performance overhead the first time a JSP is accessed via the web server. Subsequent hits however will access the cached servlet. Some web servers allow for the pre-compilation of JSPs into servlets. However, the there will still be some time taken up by the JSP engine as it determines which servlet to invoke and whether or not it needs to be re-generated.

Problems with JavaServer pages

There a several major criticisms put forward regarding JavaServer page technology. In an article entitled The Problems with JSP, Jason Hunter identifies the following issues:

  • it is too tempting to insert Java code in web pages
  • some tasks can only be done using Java code within the page
  • some simple tasks are made overly difficult
  • looping is unnecessarily difficult
  • JSP page syntax errors are cryptic and often useless
  • unless JSPs are pre-compiled, the web server will need to be equipped with a compiler
  • JSPs consume both extra hard disk and extra memory space

The use of an alternative technology, collectively termed "template engine" technology, has been put forward as a way of addressing these problems. Template engines are similar to JSPs in that they separate form and function through the uses of special tags embedded into HTML pages. However, unlike JSPs, these templates are not compiled into servlets. This simplifies the process and allows for a cleaner syntax. One such template engine, WebMacro, provides a framework for use in conjunction with standard Java servlets. A future investigation will focus on this "free" technology.


Online Resources


Appendix 1: Camtech Intranet front page

Camtech's Intranet front page has been re-written to utilise JSP technology and JavaBeans. The source code for the Java-specific components is provided here.


Appendix 2: URLEncodingServerPage2

The example discussed in the main body of this document has been rewritten to make use of a JavaBean to encapsulate the (albeit minimal) business logic.


Date: Saturday, July 8, 2000 7:14 PM