Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

JVM Languages

Java Q&A


Dec99: Java Q&A

Paul is a member of the R&D staff at Cap Gemini Telecommunications. He can be reached at [email protected].


The usefulness of static HTML has run its course and web sites whose sole content is comprised of static HTML pages are now often dismissed as "brochureware." The real world is dynamic and web pages that want to reflect this must be capable of accommodating this dynamism. It is possible, however, to deliver dynamic data content to otherwise static HTML pages by leveraging the power of Java and JavaServer Pages (JSP).

Listing One is a simple JSP. You can see that the text in the unshaded areas is recognizable as HTML. This means not only that getting started with JSP is easy, but also that you do not have to give up your favorite HTML authoring tool. You can also see that the text in the shaded area is as familiar to Java programmers as the text in the unshaded areas is to HTML authors -- it is Java code that creates an instance of GregorianCalendar for the Eastern time zone and invokes the object's getTime() method. Figure 1, the output displayed from the .jsp file in Listing One, is accessed using Internet Explorer.

Now look at Listing Two, which should look somewhat familiar if you have examined the Snoop servlet that is delivered as an example with many of the leading servlet engines. As with Listing One, you can see that Listing Two contains a combination of HTML and Java code. The Java code invokes a number of methods on an instance of Request resulting in the output in Figure 2. The browser used in this case is Netscape Navigator.

Finally, look at Listing Three, which contains a more complex JSP page representative of what you might typically encounter in the real world. Like the previous two, it consists of HTML and Java code, as well as some directives I'll discuss when showing how this JSP page, in conjunction with an HTML page and two other JSP pages, delivers dynamic data to a browser.

The Definition of a JavaServer Page

A JavaServer Page is a collection of JSP elements and fixed-template data that describes how to process a request to create a response. There are two types of JSP elements -- directives and actions.

Directives provide information to the JSP engine. Lines 12, 13, 14, and 23 in Listing Three are examples of directives. Actions can create objects that can be manipulated by scripting elements that are written using the language specified by the language attribute of the page directive. Although the JSP specification makes provisions for multiple languages, I will discuss only Java. The three scripting elements are:

  • Declarations, which have the syntax <%! declaration %>, declare a variable or method that then becomes available to other scripting elements. Line 36 in Listing Three is a declaration. Declarations produce no output to the output stream.

  • Scriptlets, which have the syntax <% code fragment %>, contain code that is executed at request-processing time. The code can create new objects, modify existing objects, and perform branching and iterative operations. In short, scriptlets can perform any operation permitted by the language in which it is written. Scriptlets may or may not produce output to the output stream.

  • Expressions, which have the syntax <%= expression %>, contain a single expression written in the scripting language. The result of the evaluation of this expression must be able to be coerced into a String that is inserted into the output stream. Lines 20-23 in Listing One, line 23 in Listing Two, and line 32 in Listing Three are all expressions.

All text in the JSP page that does not fall into one of these categories (that is, has no meaning to the JSP engine) is called "fixed-template data" and is emitted unchanged to the output stream in the order in which it appears. All unshaded text in Listings One, Two, and Three is fixed-template data.

JavaServer Pages at Work

The application I present here is a listbox from which you can select a month. After you select the month and click a button, a table containing a list of the articles in the 1999 issue of Dr. Dobb's Journal for the month you selected is displayed. If you fail to select a month, an error screen is displayed. If you select a month for which no data is available, a screen listing the available months is displayed.

Figure 3 shows the application's initial screen. Listing Four (ArticleLister.html) is the HTML that generates this screen. The difference between the form tag <form method=''post'' action=''ArticleLister.jsp''> and other form tags presented up to now is that the target of the action is not a CGI program or a servlet but rather a JavaServer page -- it is the one in Listing Three.

Every JSP page has a corresponding implementation class generated once by the JSP Engine and reused. The Engine starts by creating an empty translation unit consisting of six basic sections -- the implementation class declaration, declaration section, generated method signature, initialization section, main section, and generated method closure. It then adds to the first section the Java source code declaring the implementation class. The name of the class is implementation specific. The Engine next populates the initialization section with code that defines and initializes a number of implicit objects available to the JSP page. You have already seen one such object, the request object, on line 23 in Listing Two. Other implicit objects are response, pageContext, session, application, out, config, and page. The Engine then creates a method signature and method closure for the _jspService() method. This method's signature looks like:

void _jspService(ServletRequestSubclass request,

ServletRequestSubtype response) throws IOException,

ServletException {

Next, the Engine processes the page source as follows:

1. The first block of unshaded lines (lines 1-11) contains no syntax that is meaningful to the JSP engine This means that these lines are fixed-template data that is inserted unchanged onto the output stream. The JSP Engine inserts into the main section of the translation unit Java code that looks like: out.print(fixed template data);

2. Lines 12-14 all begin with the characters "<%@." This makes these lines directives. The first directive notifies the JSP Engine that the scripting language is Java and that all of the public types in the package "ddj" are accessible from the scripting language by their simple names rather than their fully qualified names. The second directive instructs the JSP Engine to generate code that makes the string "DDJ Article Lister V1.0" available for return by an implementation of the Servlet.getServletInfo() method. The third directive designates the page "errorpage.jsp" as the page that will handle exceptions thrown by the current page. If you examine Listing Five (errorpage.jsp), you will see that line 12 contains the directive ''<%@ isErrorPage=''true'' %>. This directive instructs the JSP Engine to make available to the scripting language of this page an implicit variable exception. This variable contains a reference to the Throwable thrown by the page in error. You can see that line 17 of errorpage.jsp contains an expression that invokes the getMessage() method of the Throwable. The String returned by this method is inserted into the output stream.

3. Line 15 contains a useBean action. The term "useBean" is perhaps somewhat ambiguous because although this action can indeed refer to an instance of a JavaBean as expected by the instantiate() method of the java .beans.Beans class and as named by the beanName attribute, it can also refer to an instance of the class named by the class attribute. The beanName and class attributes of the "useBean" action are mutually exclusive. In both cases, a reference to the instance is assigned to the scripting variable whose name is the value specified by the id attribute. In the present case, a reference to an instance of ddj.Articles is assigned to the scripting variable articles. The code for the ddj.Articles class is in Articles.java (available electronically; see "Resource Center," page 5).

The scope attribute modifies the behavior of the id attribute. It determines the namespace and lifecycle of the object reference associated with the scripting variable named by the id attribute and also determines the API used to access the referenced object; see Table 1.

4. Lines 17-22 contain a scriptlet that is a code fragment. Scriptlets are added unchanged to the main section of the translation unit.

5. Line 23 is a directive that instructs the JSP Engine to process the JSP source in file NoData.jsp (available electronically) in the same way a C-language preprocessor would process a #include statement. By using the include directive you can place common code in a single file rather than having a copy of it in multiple places. It also makes the JSP page more readable.

6. Lines 24-27 comprise a scriptlet containing the remainder of the Java code started in lines 17-22. This code is added to the main section of the translation unit.

7. Lines 28-31 contain more fixed-template data that is processed as in paragraph 1.

8. Line 32 is an expression. The Engine generates Java code that coerces the result of the expression to a String and inserts it into the output stream. This code looks like this: out.print(Stringified expression);.

9. Lines 33-35 contain more fixed-template data that is processed as in paragraph 1.

10. Line 36 is a declaration that makes the array alternatingColors available for subsequent use in line 41. The declaration is added to the declaration section of the translation unit.

11. Lines 37-39 form a scriptlet containing part of the code required to iteratively process articleList and scriptlet code is added as is to the main section of the translation unit.

12. Line 40 is fixed-template data that is processed as in paragraph 1.

13. Line 41 is an expression for alternating the colors and is processed as in paragraph 8.

14. Lines 42-44 are fixed-template data that is processed as in paragraph 1.

15. Line 45 is an expression representing the title of the article in element i of the articleList array and is processed as in paragraph 8.

16. Lines 46-49 are fixed-template data that are processed as in paragraph 1.

17. Line 50 is an expression representing the author of the article in element i of the articleList array. It is processed as in paragraph 8.

18. Lines 51-53 are fixed-template data that are processed as in paragraph 1.

19. Lines 54-56 form a scriptlet to end the for loop started in line 38. The scriptlet code is processed as in paragraph 4.

20. Lines 57-61 are fixed-template data that are processed as in paragraph 1.

21. Lines 62-64 are scriptlet code terminating the else statement in line 26. The scriptlet code is processed as in paragraph 4.

22. Lines 65-66 are fixed-template data that are processed as in paragraph 1.

The Engine now concatenates all six sections to form a complete translation unit, which is passed to the Java compiler. If compilation is successful, a .class file containing the bytecode for the JSP Page implementation class is created. The most important component of this file is the _jspService() method that is invoked at each client request. The arguments to this method are request and response. These arguments are subInterfaces of javax.servlet.ServletRequest and javax.servlet.ServletResponse, respectively.

When you run the Article Lister application, the first time you select a month and click on the GET ARTICLES button you will experience a noticeable delay. This delay is the result of the translation/compilation process. Subsequent requests are faster because they involve only invocation of the _jspService() method.

Invocation of the _jspService() method results in the following:

  • The out.print() statements are executed and they insert the fixed-template data in lines 1-11 into the output stream.

  • The Java code resulting from lines 18-20 in Listing Three invokes the processRequest() method of articles, which is an instance of ddj.Articles passing request (an implicit object) as an argument.

  • Lines 137-139 in Articles.java (available electronically) invoke the getParameter() method of request passing it the argument ''month,'' which is the name of the <select> HTML element in line 21 of Listing Four (ArticleLister.html). If the result is null (meaning no month was selected), an exception is thrown. This exception is caught by the code generated by the JSP Engine for errorpage.jsp (available electronically). This code sends HTML to the output stream resulting in the browser page in Figure 4. If the result is not null, setMonth() is invoked to save the value of the selected month in an instance variable for subsequent retrieval using the getMonth() method. The code resulting from lines 18-20 of Listing Three invokes the getMonth() method of articles and passes the returned month to the getArticles() method, which returns a 2D String array containing a list of the articles and corresponding authors. If the length of the returned array is zero (meaning no data is available), the code generated from NoData.jsp (available electronically) is executed resulting in the browser page in Figure 5. Finally, the for loop generated from lines 37-39, 41, 45, 50, and 54-56 is executed. This loop creates a table, which is displayed in the browser page in Figure 6.

Conclusion

To fully realize the power of JSP technology, imagine if you replaced the ArticleLister class with Enterprise Java Beans that communicated with large databases or other Enterprise resources (including other computers), and replaced the simple list of articles and their authors with the results of complex queries or transactions.

My discussion of JavaServer Pages is by no means exhaustive. Much more detailed information about JSP can be obtained from the JavaServer Pages Specification, available at http://java.sun.com/products/jsp/.

DDJ

Listing One

   1| <!doctype html public "-//w3c//dtd html 4.0 transitional//en">
   2| <html>
   3| <head>
   4| <title>JSP Example 1</title>
   5| <meta http-equiv="Content-Type" content="text/html; 
   6|   charset=iso-8859-1">
   7| <meta name="Author" content="Paul Tremblett">
   8| <meta name="GENERATOR" content="Mozilla/4.51 [en] (X11; I; 
   9|   Linux 2.2.5-15 i586) [Netscape]">
  10| </head>
  11| <body bgcolor="#FFFFFF">
  12| <p>
  13| <font face="Arial, Helvetica, sans-serif"><b><font size="+2">
  14| JSP Example 1 
  15| </font></b></font>
  16| <br>
  17| <br>
  18| <font face = "Arial, Helvetica"><font size="+1">
  19| It is now
  20| <%=
  21| new java.util.GregorianCalendar(new java.util.SimpleTimeZone
  22|    (-5*60*60*1000,"EDT")).getTime()
  23| %>
<pre>  24| </font>
  25| </body>
  26| </html>

Back to Article

Listing Two

   1| <!doctype html public "-//w3c//dtd html 4.0 transitional//en">
   2| <html>
   3| <head>
   4| <title>JSP Example 2</title>
   5| <meta http-equiv="Content-Type" content="text/html; 
   6|   charset=iso-8859-1">
   7| <meta name="Author" content="Paul Tremblett">
   8| <meta name="GENERATOR" content="Mozilla/4.51 [en] (X11; I; 
   9|   Linux 2.2.5-15 i586) [Netscape]">
  10| </head>
  11| <body bgcolor="#FFFFFF">
  12| <p>
  13| <font face="Arial, Helvetica"><b><font size="+2">
  14| <center>
  15| JSP Example 2 
  16| </font></b></font><br>
  17| <br>
  18| <font face = "Arial, Helvetica, sans-serif"><font size="+1">
  19| <b><u>Some Info About Your Request:</u></b>
  20| </center>
  21| <br>
  22| Protocol: 
  23| <%= request.getProtocol() %>
<pre>  24| <br>
  25| Remote Addr: 
  26| <%= request.getRemoteAddr() %>
<pre>  27| <br>
  28| Remote Host: 
  29| <%= request.getRemoteHost() %>
<pre>  30| <br>
  31| URL Scheme: 
  32| <%= request.getScheme() %>
<pre>  33| <br>
  34| Server Name: 
  35| <%= request.getServerName() %>
<pre>  36| <br>
  37| Server Port: 
  38| <%= request.getServerPort() %>
<pre>  39| </font>
  40| </body>
  41| </html>

Back to Article

Listings Three

   1| <!doctype html public "-//w3c//dtd html 4.0 transitional//en">
   2| <html>
   3| <head>
   4| <title>DDJ Article Lister</title>
   5| <meta http-equiv="Content-Type" content="text/html; 
   6|   charset=iso-8859-1">
   7| <meta name="Author" content="Paul Tremblett">
   8| <meta name="GENERATOR" content="Mozilla/4.51 [en] (X11; I; 
   9|   Linux 2.2.5-15 i586) [Netscape]">
  10| </head>
  11| <body bgcolor="#FFFFFF">
  12| <%@ page language="java" import="ddj.*" %>
  13| <%@ page info="DDJ Article Lister V1.0" %>
  14| <%@ page errorPage="errorpage.jsp" %>
  15| <jsp:useBean id="articles" scope="request" 
  16|   class="ddj.Articles" />
  17| <%
  18|   articles.processRequest(request);
  19|   String month = articles.getMonth();
  20|   String[][] articleList = articles.getArticles(month);
  21|   if (articleList.length == 0) {
  22| %>
  23| <%@ include file = "NoData.jsp" %>
  24| <%
  25|   }
  26|   else {
  27| %>
<pre>  28| <center>
  29| <table cellspacing=0 cols=2 width="80%">
  30| <caption><b><font face="Arial, Helvetica"><font size=+1>
  31| Dr. Dobb's Articles For The Month Of
  32| <%= month %>
<pre>  33| 1999
  34| </font></font></b>
  35| </caption>
  36| <%! String[] alternatingColors = {"#ffff99", "#ffcc99"}; %>
  37| <%
  38|     for (int i = 0; i < articleList.length; ++i) {
  39| %>
<pre>  40| <tr bgcolor=
  41| <%=alternatingColors[i % 2] %>
<pre>  42| >
  43| <td>
  44| <b>
  45| <%= articleList[i][0] %>
<pre>  46| </b>
  47| </td>
  48| <td>
  49| <b>
  50| <%= articleList[i][1] %>
<pre>  51| </b>
  52| </td>
  53| </tr>
  54| <%
  55|     }
  56| %>
<pre>  57| </table>
  58| <form method=get action="ArticleLister.html">
  59| <input type=submit name="submit" value="BACK">
  60| </form>
  61| </center>
  62| <%
  63|   }
  64| %>
<pre>  65| </body>
  66| </html>

Back to Article

Listing Four

<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<title>DDJ Article Lister</title>
<meta http-equiv="Content-Type" content="text/html; 
  charset=iso-8859-1">
<meta name="Author" content="Paul Tremblett">
<meta name="GENERATOR" content="Mozilla/4.51 [en] (X11; 
  I; Linux 2.2.5-15 i586) [Netscape]">
</head>
<body bgcolor="#FFFFFF">
<p>
<font face="Arial, Helvetica, sans-serif"><b><font size="+2">
<center>
DDJ Article Lister
</font></b></font><br>
<br>
<font face = "Arial, Helvetica, sans-serif"><font size="+1">
Select a month from the list below:
<form method="post" action="ArticleLister.jsp">
<select name="month" size=4>
<option value="January">January
<option value="February">February
<option value="March">March
<option value="April">April
<option value="May">May
<option value="June">June
<option value="July">July
<option value="August">August
<option value="September">September
<option value="October">October
<option value="November">November
<option value="December">December
</select>
<br>
<br>
<br>

<input type="submit" name="submit" value="GET ARTICLES">
</form>
</center>
</body>
</html>

Back to Article

Listing Five

<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<title>DDJ Article Lister</title>
<meta http-equiv="Content-Type" content="text/html; 
  charset=iso-8859-1">
<meta name="Author" content="Paul Tremblett">
<meta name="GENERATOR" content="Mozilla/4.51 [en] (X11; I; 
  Linux 2.2.5-15 i586) [Netscape]">
</head>
<body bgcolor="#ff0000">
<%@ page isErrorPage="true" %>
<center>
<br>
<br>
<h1> Error: 
<%= exception.getMessage() %>
</h1>
<form action="ArticleLister.html">
<input type="submit" value="Try Again">
</form>
</CENTER>
</body>
</html>


Back to Article


Copyright © 1999, Dr. Dobb's Journal

Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.