Internet Programming with Java Course

1.    JavaServer Pages


JavaServer Pages (JSP) technology enables you to mix regular, static HTML with dynamically generated content from servlets. You simply write the regular HTML in the normal manner, using familiar Web-page-building tools. You then enclose the code for the dynamic parts in special tags, most of which start with <% and end with %>.


Thanks for ordering <I><%= request.getParameter("title") %></I>


Separating the static HTML from the dynamic content provides a number of benefits over servlets alone, and the approach used in JavaServer Pages offers several advantages over competing technologies such as ASP, PHP, or ColdFusion. Section 1.4 (The Advantages of JSP) gives some details on these advantages, but they basically boil down to two facts: that JSP is widely supported and thus doesn’t lock you into a particular operating system or Web server and that JSP gives you full access to servlet and Java technology for the dynamic part, rather than requiring you to use an unfamiliar and weaker special-purpose language. The process of making JavaServer Pages accessible on the Web is much simpler than that for servlets. Assuming you have a Web server that supports JSP, you give your file a .jsp extension and simply install it in any place you could put a normal Web page: no compiling, no packages, and no user CLASSPATH settings. However, although your personal environment doesn’t need any special settings, the server still has to be set up with access to the servlet and JSP class files and the Java compiler. For details, see your server’s documentation or Section 1.5 (Installation and Setup). Although what you write often looks more like a regular HTML file than a servlet, behind the scenes, the JSP page is automatically converted to a normal servlet, with the static HTML simply being printed to the output stream associated with the servlet’s service method. This translation is normally done the first time the page is requested. To ensure that the first real user doesn’t get a momentary delay when the JSP page is translated into a servlet and compiled, developers can simply request the page themselves after first installing it. Many Web servers also let you define aliases so that a URL that appears to reference an HTML file really points to a servlet or JSP page.


Aside from the regular HTML, there are three main types of JSP constructs that you embed in a page: scripting elements, directives, and actions. Scripting elements let you specify Java code that will become part of the resultant servlet, directives let you control the overall structure of the servlet, and actions let you specify existing components that should be used and otherwise control the behavior of the JSP engine. To simplify the scripting elements, you have access to a number of predefined variables, such as request in the code snippet just shown. Scripting elements are covered in this chapter, and directives and actions are explained in the following chapters.

Scripting Elements

JSP scripting elements let you insert code into the servlet that will be generated from the JSP page. There are three forms:

1. Expressions of the form <%= expression %>, which are evaluated

and inserted into the servlet’s output

2. Scriptlets of the form <% code %>, which are inserted into the

servlet’s _jspService method (called by service)

3. Declarations of the form <%! code %>, which are inserted into

the body of the servlet class, outside of any existing methods

Each of these scripting elements is described in more detail in the following


Template Text

In many cases, a large percentage of your JSP page just consists of static HTML, known as template text. In almost all respects, this HTML looks just like normal HTML, follows all the same syntax rules, and is simply “passed through” to the client by the servlet created to handle the page. Not only does the HTML look normal, it can be created by whatever tools you already are using for building Web pages. There are two minor exceptions to the “template text is passed straight through” rule. First, if you want to have <% in the output, you need to put <\% in the template text. Second, if you want a comment to appear in the JSP page but not in the resultant document, use <%-- JSP Comment --%> HTML comments of the form <!-- HTML Comment -->

are passed through to the resultant HTML normally.

JSP Expressions

A JSP expression is used to insert values directly into the output. It has the following form:


<%= Java Expression %>


The expression is evaluated, converted to a string, and inserted in the page. This evaluation is performed at run time (when the page is requested) and thus has full access to information about the request. For example, the following shows the date/time that the page was requested:


Current time: <%= new java.util.Date() %>

JSP Scriptlets

If you want to do something more complex than insert a simple expression, JSP scriptlets let you insert arbitrary code into the servlet’s _jspService method (which is called by service). Scriptlets have the following form:


<% Java Code %>


Scriptlets have access to the same automatically defined variables as expressions (request, response, session, out, etc). So, for example, if you want output to appear in the resultant page, you would use the out variable, as in the following example.



String queryData = request.getQueryString();

out.println("Attached GET data: " + queryData);



In this particular instance, you could have accomplished the same effect more easily by using the following JSP expression:


Attached GET data: <%= request.getQueryString() %>


In general, however, scriptlets can perform a number of tasks that cannot be accomplished with expressions alone. These tasks include setting response headers and status codes, invoking side effects such as writing to the server log or updating a database, or executing code that contains loops, conditionals, or other complex constructs. For instance, the following snippet specifies that the current page is sent to the client as plain text, not as HTML (which is the default).


<% response.setContentType("text/plain"); %>


It is important to note that you can set response headers or status codes at various places within a JSP page, even though this capability appears to violate the rule that this type of response data needs to be specified before any document content is sent to the client. Setting headers and status codes is permitted because servlets that result from JSP pages use a special type of PrintWriter (of the more specific class JspWriter) that buffers the document before sending it. This buffering behavior can be changed, however; see Section 11.6 for a discussion of the autoflush attribute of the page directive.


As an example of executing code that is too complex for a JSP expression the listing presents a JSP page that uses the bgColor request parameter to set the background color of the page. Some results are shown in Figures




<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">



<TITLE>Color Testing</TITLE>



    String bgColor = request.getParameter("bgColor");

    boolean hasExplicitColor;

    if (bgColor != null) {

        hasExplicitColor = true;

    } else {

        hasExplicitColor = false;

        bgColor = "WHITE";



<BODY BGCOLOR="<%= bgColor %>">

<H2 ALIGN="CENTER">Color Testing</H2>


    if (hasExplicitColor) {

        out.println("You supplied an explicit background color of " +

        bgColor + ".");

    } else {

        out.println("Using default background color of WHITE. " +

        "Supply the bgColor request attribute to try " +

        "a standard color, an RRGGBB value, or to see " +

        "if your browser supports X11 color names.");





Default result of BGColor.jsp.


Result of BGColor.jsp when accessed with a bgColor parameter having the RGB value C0C0C0.

Using Scriptlets to Make Parts of the JSP File Conditional

Another use of scriptlets is to conditionally include standard HTML and JSP constructs. The key to this approach is the fact that code inside a scriptlet gets inserted into the resultant servlet’s _jspService method (called by service) exactly as written, and any static HTML (template text) before or after a scriptlet gets converted to print statements. This means that scriptlets need not contain complete Java statements, and blocks left open can affect the static HTML or JSP outside of the scriptlets. For example, consider the following JSP fragment containing mixed template text and scriptlets.


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

    Have a <B>nice</B> day!

<% } else { %>

    Have a <B>lousy</B> day!

<% } %>


When converted to a servlet by the JSP engine, this fragment will result in something similar to the following.


if (Math.random() < 0.5) {

    out.println("Have a <B>nice</B> day!");

} else {

    out.println("Have a <B>lousy</B> day!");



The page directive lets you control the structure of the servlet by importing classes, customizing the servlet superclass, setting the content type, and the like. A page directive can be placed anywhere within the document; its use is the topic of this chapter. The second directive, include, lets you insert a file into the servlet class at the time the JSP file is translated into a servlet. An include directive should be placed in the document at the point at which you want the file to be inserted;

The page directive lets you define one or more of the following case-sensitive attributes: import, contentType, isThreadSafe, session, buffer, autoflush, extends, info, errorPage, isErrorPage, and language. These attributes are explained in the following sections.

The import Attribute

The import attribute of the page directive lets you specify the packages that should be imported by the servlet into which the JSP page gets translated. If you don’t explicitly specify any classes to import, the servlet imports java.lang.*, javax.servlet.*, javax.servlet.jsp.*, javax.servlet.

http.*, and possibly some number of server-specific entries. Never write JSP code that relies on any server-specific classes being imported automatically. Use of the import attribute takes one of the following two forms:


<%@ page import="package.class" %>

<%@ page import="package.class1,...,package.classN" %>


For example, the following directive signifies that all classes in the java.util package should be available to use without explicit package identifiers.


<%@ page import="java.util.*" %>


The import attribute is the only page attribute that is allowed to appear multiple times within the same document. Although page directives can appear anywhere within the document, it is traditional to place import statements either near the top of the document or just before the first place that the referenced package is used.

The contentType Attribute

The contentType attribute sets the Content-Type response header, indicating the MIME type of the document being sent to the client. For more information on MIME types.

Use of the contentType attribute takes one of the following two forms:


<%@ page contentType="MIME-Type" %>

<%@ page contentType="MIME-Type; charset=Character-Set" %>


For example, the directive


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


has the same effect as the scriptlet


<% response.setContentType("text/plain"); %>


Unlike regular servlets, where the default MIME type is text/plain, the

default for JSP pages is text/html (with a default character set of ISO-8859-1).