JavaServer Pages in a Nutshell

Need an eye-catching Web presence that provides dynamic, up-to-the-minute content? JavaServer Pages (JSPs) provide Web developers with a construction tool that separates presentation and business logic. Drill down and discover what JavaServer Pages can do for the enterprise.

Sites that contained static content dominated the early days of the Web: "What you saw was what you got" back then. These days, companies want their Web sites to contain dynamic content that reflects real world conditions.

Web developers constructing elaborate Web sites need technology that allows for the separation of business logic from presentation. This way, the Web developer can freely change code for one tier without impacting the other tier.

Sun Microsystems and other industry leaders published Java 2 Enterprise Edition (J2EE) [see Andy Patrizio's "J2EE on the March"]. J2EE defines a computing platform for the creation of enterprisewide, distributed object-based applications using Java technology. What one technology may be helpful to anyone concerned with the above three issues? The answer is JavaServer Pages (JSPs).

JSP Overview

JSPs describe a framework that allows Web developers to create dynamic content using HTML, XML or other templates mixed with Java code. The short story is that the JSP developer codes the parts of the Web page that do not change as usual, using HTML or XML; the developer codes the parts of the Web page that change using JSP commands. This framework is simpler than coding Java servlets, where the servlet developer must write Java code to produce HTML or XML for all parts of the page, whether the page part changes or not.

The JSP API extends the Java Servlets API; indeed, a JSP gets translated to a servlet the first time the JSP is invoked. However, you need not know the nuts and bolts of writing Java servlets in order to write and deploy JSPs. The JSP developer does not compile a JSP. The servlet engine handles the translation of a JSP into a servlet (and the compilation of the resultant servlet). Typically, this translation process occurs only once, when the JSP page is first requested. Also, the servlet engine loads only one copy of the resultant servlet. If a client requests the same JSP page several times, the servlet engine is smart enough to use the resultant servlet already loaded, as opposed to loading multiple copies of the servlet translated from the JSP page. The servlet remains resident until the servlet engine is shut down or explicitly purged.

JSPs use a combination of tags that eventually get generated into Java code combined with static text, usually HTML or XML. These tags allow the JSP developer to embed Java code, declare variables and invoke Java beans. A benefit of this architecture is that the artists among us can develop the static parts of the page separate from the programmers among us who can develop the dynamic parts. Changes in the static parts usually have little or no impact on the dynamic parts. This is in sharp contrast to Java servlets, where a change in any part of the page requires repetition of the compilation/deployment process.

JSP is not the only technology that addresses the problem of providing dynamic Web page content. Other technologies include Active Server Pages (Microsoft), Common Gateway Interface (CGI) and various scripting languages (PHP, for example). All these technologies, including JSP, have strong and weak points. However, the developer using JSPs is not locked into any particular hardware or server platform and has all the strengths and features of the Java programming language at her disposal.

Let's take a look at a simple JSP next.

A Simple JSP

Table 1 is an example of a JSP that provides dynamic content. This page displays the date and the time. First, the code that produces the page with a bit of emphasis on the JSP code.

<html>

<body

<font size="+2">

<br><br>

center><b>The Time and Date is:

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

<b></center>

</font>

</body>

</html>

Table 1: A JSP Page that Displays the Current Data and Time

The page requester would see this text in a browser: The Time and Date is: Mon May 07 9:41:22:25 EST 2001.

Notice the single line of the page that generates the date and time. The Java servlet resulting from the translation of this JSP page contains the following print statement:

out.print(new java.utilDate() ) ;

The JSP Life Cycle

A JSP page is executed by a JSP engine (sometimes called a container). This engine is installed on a Web or application server. The JSP engine handles the JSP translation into a servlet, as well as handling the request and response objects sent to and from the server.

The JSP author may write code that the container translates into a jspInit() method to perform initializations. This method, if coded, will execute only once, like the init() method of servlets and applets. Also, the JSP author may write code that gets translated into a jspDestroy() method to perform cleanup. The JSP specification does not require JSP authors to write code that will generate either of these methods. However, some JSP engine implementations will generate jspInit() and jspDestroy() methods internally, which a JSP author may override.

The JSP container will translate the JSP page body into the _jspService method, analogous to the service() method coded in servlets. Whereas the JSP author may code an implementation for jspInit() and jspDestroy, the JSP author should not write any JSP code that gets translated into an implementation of the _jspService() method; that's the job of the JSP translator.

Elements of a JSP Page

As previously mentioned, a JSP page is a mixture of static text and JSP elements. Put differently, the JSP elements are what gets processed on the server. Here, we'll take a quick look at the elements of a JSP page. The JSP element classifications are directives, scripting elements, standard actions and implicit JSP objects.

JSP Directives

A JSP directive is used to set values global to the JSP page. Directives do not produce any output to the client. A directive has the following form:

<%@ directiveName someAttribute1="attrValue1" someAttrubite2="attrValue2 ... %>

where directiveName can be include, page or taglib. Pay note to the space between the at sign and the directive name.

The include directive causes the JSP container to include the content of a file in the JSP. An example of the include directive is:

<%@ include file='somefilename' %>

The content of the file represented by somefilename is brought in the JSP at translation time. JSP supports an include action which a JSP author may use to include content at JSP runtime. The JSP author should not include a file at translation time that contains dynamic content.

The page directive allows the JSP author to define various attributes that apply to the entire page. The basic format of the page directive is:

<%@ page attrib1="attr1Value" ... attribn="attribnValue" %>

The page directive takes a number of attributes. Here is an example of a page directive coded with multiple attributes:

<% page import="java.util.*,java.io.*", session="false", isErrorPage="false",

errorPage="myErrorPage.html", buffer="24kb", autoFlush="true" %>

With the exception of the import attribute, only one of these attributes may appear in a JSP.

The taglib directive tells the JSP engine to use custom user-defined tags. The mechanism is that the directive names a file that contains the tags and specifies a prefix used within the JSP page to identify a custom tag.

The general form of the taglib directive is:

<%@ taglib uri="tagLibraryLocation" prefix="identifyingPrefix" %>

The JSP author coding a taglib directive must provide a value for the uri and prefix attributes. The prefixes jsp, jspx, java, javax, servlet, sun and sunw are reserved.

For example, this taglib directive:

<%@ taglib uri=http://www.louserver.com/loustags prefix="loustags" %>

tells the JSP engine that tags with a prefix of loustags, like <loustags:atag> ....</loustags:atag> are defined in the value of the uri attribute coded above. This uri contains java code that implements the custom tags.

JSP Scripting Elements

The JSP author uses scripting elements to include Java code in the page. JSP scripting elements may include declares, which define classes and methods to the page. JSP scripting elements may include scriptlets, which are blocks of Java code executed at JSP page request time. JSP scripting elements may include expressions, which are shorthand for directing output to the response stream back to the client.

JSP declares, or declarations, are enclosed in <%! ... %>.

Here's an example of some declarations:

<%! int aVar=0, bVar=10;

public String theGeneratedStringValue() {

// Java Code Here

return locString ;

}

%>

The JSP engine places this code verbatim into the translated servlet. The code corresponding to the declarations is executed when the JSP page is initialized.

In contrast, scriptlets contain Java code that gets executed at request time. The code is enclosed in <% ... %>. Here's an example of a scriptlet:

<% for (int idx=0; idx < 10; idx++) {

out.println("<b>This text is bold</b> and <i>this text is italic </i>" ) ;

}

%>

At first, there seems to be little difference between scriptlets and declarations aside from the syntax of the enclosing brackets.

However, scriptlets need not contain complete Java statements. For example, this scriptlet allows the mixture of HTML and Java code to conditionally generate content:

<% if (Math.random() < .5) { %>

<b>This text is bold</b>

<% } else { %>

<i> This text is italic </i>

<% } %>

Notice how the JSP author may include different "pieces" of Java code. When all scriptlets are combined, the result must be syntactically correct Java code or translation errors will occur.

JSP expressions are convenient shorthand statements that direct output to the client. Expressions are coded between <%= .... %>.

Here's an example of a JSP expression:

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

The resultant code gets placed in the servlets _jspService method.

JSP Standard Actions

JSP implementations must support a set of actions that affect the runtime behavior of the JSP. These actions, coded as tags, are called standard actions; the JSP implementor is free to support other actions above and beyond the standard set.

The actions allow a JSP author to access JavaBeans, to get and set bean properties for later use, to include content at request time, to forward requests to a different JSP page and to load plug-ins.

JSP Implicit Objects

The JSP container exposes various objects to pages. The JSP author does not declare these objects. These objects are available to expressions and scriptlets (not declarations). These objects have a particular scope; they are known anywhere in the current page, response, request, session or application. These implicit objects are instances of various server classes.

<html>

<font size="+2">

<br><br><br>

Session ID:

<%= session.getId() %>

<br>

Session Created On:

<%= session.getCreation-Time() %>

<br>

Last Time Session Accessed Was:

<%=session.getLastAccessedTime() %>

</html>

Table 2: An Example of a JSP Page

 

Rather than having to write Java to access these objects by providing import statements or qualifying their classes, these often used and useful objects are immediately known to JSP pages. In the example in Table 2, this JSP can access various properties of its session. Notice the bolded JSP expressions that refer to the session implicit object.

In Closing

JavaServer Pages and Java Servlets form part of the Java 2 Platform for Enterprise Applications (J2EE), which provides tools and functionality for server and distributed Web applications. JSPs extend Java into the realm of providing dynamic Web content without having to write Java servlets. The page designer need not be a Java guru to author JSP. In short, JSP allows the author to tap the power of Java without having to know most of the messy details.

Lou Marco is a writer, technical instructor and a consultant with over 20 years of computing experience. He is the author of ISPF/REXX Development for Experienced Programmers. He can be reached at loumarco@hotmail.com.