Intro to JavaServer pages

Java Server Pages (JSPs) allow you to create dynamically generated Web pages that are cross platform. We'll walk you through an example.

By John Zukowski

JavaServer Pages (JSP) is the Java-based technology for generating dynamic Web pages with cross-platform and cross-Web-server support.

JSP is comparable to Microsoft's Active Server Pages, but uses HTML-like tags and Java code snippets instead of VBScript. Consider JSP when you're working with a Web server that doesn't offer native ASP support, that is, Apache or Netscape servers. You can get an ASP add-on module for these servers, but it's pricey, and for the moment Sun isn't charging a licensing fee for what you need for JSP (although it may in future). The components are also easy to get for Solaris and Linux as well as Windows.

Don't confuse JSP with server-side JavaScript. The Web server automatically converts the Java code snippets created with JSP to Java servlets. JSP also automates control for many capabilities previously hand-coded with Perl scripts or server-specific APIs such as ASP.

We're going to get you started and help you build a sample JSP-enabled site.

Get your machines ready for JSP
You'll need a Java 2 Software Development Kit (JSDK), previously known as a Java Development Kit (JDK), and a JavaServer Web Development Kit (JSWDK), Tomcat, or other Web server that supports JSP. Sun offers the JSDK and JSWDK free for the Windows, Solaris, and Linux platforms.

If you want to use JSP with your present Web server, and the server itself doesn't support JSP and Java servlets, try Macromedia's JRun, which acts as a Web server add-on for Netscape's Enterprise and FastTrack Servers, Microsoft's Internet Information Server (IIS) and Personal Web Server (PWS), Apache, and other servers. You can also use the Java version of the Apache Web server, included in the latest JSWDK.

Downloading and installing what you need
Currently at release 1.2.2-001, the JSDK downloadable version comes as an installable archive. The approximately 20MB download provides a complete Java development environment, letting you create any Java-based solutions that utilize the core, standard APIs. However, the only thing your Web server needs to work with JSP is access to the Java compiler. To tell the Web server the location of the compiler, set the JAVA_HOME environment variable to the JSDK installation directory. If you've installed on Windows and have accepted the default directory, add the line set JAVA_HOME=C:\1.2.2 to your autoexec.bat file and restart.

After installing the JSDK, download and install either the JSWDK or a beta release of Tomcat, the Java-based Apache Web server. The specifics of where you place this is really irrelevant, as long as you can find it again. Normally, it is just placed in a top-level directory, as this lets you replace the JSWDK or JSDK version without requiring you to move the other. After you've installed this file, you're ready for JSP development.

Once you've installed the JSWDK properly, run the startserver script to start up the Web server to listen on port 8080 by default. To see if you've installed the tool correctly after starting the server, load up one of the sample JSP files (http://localhost:8080/examples/jsp/). If you are able to successfully run one of the sample, file, you know you've set up the software properly. If instead you see an error message in the console window used to start the server, then you need to fix it. The most frequently occurring problem is an unset (or incorrectly set) JAVA_HOME environment variable. To see the current environment settings, type set at the DOS prompt.

Getting started
Before explaining JSP syntax, create a quick Web page that displays the current date and time and save it as sample.jsp:
<title>First Page</title>
<H3>Today is:
<%= new java.util.Date() %>

Place this file and all your HTML and JSP pages in a Web pages directory under your JSWDK installation directory. You can load this page at http://localhost:8080/sample.jsp. After the Web server translates the JSP to a Java servlet the first time the page is visited, you'll see the current date and time.

Now that you've downloaded, installed, and configured the development environment, you're set to understand JSP syntax and create your own JSP-based solutions.

JSP syntax basics
Moving beyond installation, we'll now go into the JSP syntax. For a cheat sheet, you can download a syntax card. And if you're not familiar with Java programming, you may want to visit Sun's tutorial; however, Web builders shouldn't have to do too much Java development. Other than a few method calls, the Java code in your JSP Web pages should be minimal.

With that in mind, let's look first at JSP directives and scripting elements, after which we'll explain JavaBeans and implicit objects. There are five types of JSP directives and scripting elements. With JSP 1.0, most of your JSP is enclosed within a single tag that begins with <% and ends with %>. With the newer JSP 1.1 specification, there are also XML-compliant versions.
Exhibit 1
JSP directives and scripting elements
Directives <%@ directive %>
Declarations <%! declaration %>
Expressions <%= expression %>
Code Fragment/Scriptlet <% code fragment %>
Comments <%— comment —%>

JSP directives are for the JSP engine. They do not directly produce any visible output but instead tell the engine what to do with the rest of the JSP page. They are always enclosed within the <%@ … %> tag. The two primary directives are page and include. The taglib directive will not be discussed but is available for creating custom tags with JSP 1.1.

The page directive is the one you'll find at the top of almost all your JSP pages. Although not required, it lets you specify things like where to find supporting Java classes:
<%@ page import="java.util.Date" %>

where to send the surfer in the event of a runtime Java problem:
<%@ page errorPage="errorPage.jsp" %>

and whether you need to manage information at the session level for the user, possibly across multiple Web pages (more later on sessions with JavaBeans):
<%@ page session="true" %>

The include directive lets you separate your content into more manageable elements, such as those for including a common page header or footer. The page included could be a fixed HTML page or more JSP content:
<%@ include file="filename.jsp" %>

JSP declarations let you define page-level variables to save information or define supporting methods that the rest of a JSP page may need. If you find yourself including too much code, it is usually better off in a separate Java class. Declarations are found within the <%! … %> tag. Always end variable declarations with a semicolon, as any content must be valid Java statements: <%! int i=0; %>.

With expressions in JSP, the results of evaluating the expression are converted to a string and directly included within the output page. JSP expressions belong within <%= … %> tags and do not include semicolons, unless part of a quoted string:
<%= i %>
<%= "Hello" %>

Code fragments/scriptlets
JSP code fragments or scriptlets are embedded within <% … %> tags. This Java code is then run when the request is serviced by the Web server. Around the scriptlets would be raw HTML or XML, where the code fragments let you create conditionally executing code, or just something that uses another piece of code. For example, the following displays the string "Hello" within H1, H2, H3, and H4 tags, combining the use of expressions and scriptlets. Scriptlets are not limited to one line of source code:
<% for (int i=1; i<=4; i++) { %>
<% } %>

The last of the key JSP elements is for embedding comments. Although you can always include HTML comments in your files, users can view these if they view the page's source. If you don't want users to be able to see your comments, you would embed them within the <%— … —%> tag:
<%— comment for server side only —%>

JSP With JavaBeans
Although you can place large blocks of code within scriptlets, most of the Java code belongs in reusable components called JavaBeans. JavaBeans are like ActiveX controls: they provide known functionality and are designed for off-the-shelf reuse.

A JavaBean's value is made available through a set of properties, which provides access to the JavaBean's settings. Using a person as an analogy, the person would be a JavaBean, and that person's name, social security number, and address would be the properties. With JSP Web sites, you basically play "connect the beans" to get your site to be dynamic.

Assuming the JavaBean was created prior to creating the site, the first thing you need to do is tell the JSP page that it intends to use a bean. This is done with the <jsp:useBean> tag:
<jsp:useBean id="localName" class="com.jguru.Person" scope="application" />.

The <jsp:useBean> tag requires you to identify the bean with the id attribute. Here you provide a name to identify to the bean within the rest of the JSP page. In addition to the id attribute, you also must tell the page where to find the bean, or its Java class name. The class attribute provides this, among a handful of other ways to specify it. The final required element is the scope attribute. With the help of the scope attribute, you can tell the bean to maintain its information for the single page (the default) [scope="page"]; for the request [scope="request"]; for the session [scope="session"]; or for the whole application [scope="application"]. With session scope, you can maintain items such as shopping carts very easily within JSP pages.

Once you have declared a JavaBean, you have access to its properties to customize it. To get the value of a property, use the <jsp:getProperty> tag. With the <jsp:getProperty> tag, you specify the name of the bean to use (from the id field of useBean), as well as the property whose value you want to get. The actual value is then placed within the output:
<jsp:getProperty id="localName" property="name" />.

Changing the property of a JavaBean requires you to use the <jsp:setProperty> tag. For this tag, you again identify the bean and property to modify and additionally provide the new value. If named properly, these can be directly acquired from a submitted form:
<jsp:setProperty id="localName" property="*" />;

acquired from a parameter, in which you have to name the property and parameter directly:
<jsp:setProperty id="localName" property="address" param="parameterName" />;

or just directly set with a name and value:

One last thing about JavaBeans: So that the Web server can find the JavaBeans, you'll need to place their class files in a special place. With the JSWDK, the simplest place is the classes directory under the installation directory, as in \jswdk-1.0.1\classes.

JSP implicit objects
The last of the JSP syntax-related elements are something called implicit objects. Within JSP scriptlets, you have access to these implicit objects to interact with the executing servlet environment for the JSP page. Much of the access to the implicit objects should be minimized. However, there are instances in which access is acceptable. To fully utilize the implicit object set requires an understanding of the latest Java Servlet API.

The following table represents the set of implicit objects available to you.
Exhibit 2
Implicit object description
request The client request, which includes parameters from GET/POST requests
response The page's response back to the client
pageContext The attributes of the page are managed here
session The session associated with the request
application The context in which the servlet is running
out The output stream used to send the response
config The servlet configuration object
page The JSP page itself
exception For error pages, the uncaught exception

So, what are all these for, and how do you use them? Well, basically, within your scriptlets you can use them to access the servlet executing the JSP code. Without going into too many details of the Servlet API, let's examine some of the things you can do with them:
  • ·        Instead of using an expression, you can directly access the implicit out object to print something to the response:
    <% out.println("Hello"); %>.
  • ·        Instead of sending a parameter directly to a JavaBean, you can get the parameter value from the request object:
    <% String name=request.getParameter("name"); out.println(name); %>.

As you develop more with JSP, if you create JavaBeans or find yourself putting too much Java source code into your JSP files, you'll need to create supporting Java classes, which encourages reuse and decreases JSP page translation time. When you need to create Java class files, you must:
  1. 1.      Add the JDSWK installation \bin directory to your PATH. In yourautoexec.bat file's PATH line, add C:\1.2.2\bin; to the end of that line.
  2. 2.      Copy the JAR file to the \jre\lib\ext directory with the command:
    copy c:\jswdk-1.0.1\lib\servlet.jar c:\jdk1.2.2\jre\lib\ext.

Create a JSP Site
It's now time to put all this JSP syntax to use. We'll create a Web page that has an input form for a user to enter in a stock symbol and get the current stock price (delayed by 20 minutes). If there is an error, an error page is shown instead.

First, create a quote.jsp page with this code and save it in the Web pages directory under the JSWDK installation directory. Most of the page is standard HTML with JSP code interspersed. Line 6 is a page directive that says to send any error to the errorPage.jsp file. Lines 13 through 15 are a scriptlet that basically says only show the table if the "symbol" parameter is present. This if-block is closed on lines 32 through 34. Line 17 defines the JavaBean to use, and line 18 loads its symbol property from the parameter. Lines 27 through 29 just display the bean properties. Other than the if-block, there is really no Java coding involved.

Next, save the following JSP source to the file errorPage.jsp in the Web pages directory. The clue that this is an error page is the first line, which sets the page directive isErrorPage attribute to true. Whereas the prior page said where the error page is, this page says it is the error page. The only other JSP-specific code in the JSP file is the access to the implicit exception object. The page just displays its value:
<%@ page isErrorPage="true" %>
<title>Error Page</title>
<h1>Our Error Page</h1></font>
<!— Print Exception —>
We got ourselves an exception:
    <%= exception %>
<a href="quote.jsp">Restart</a>
The Quotes JavaBean uses a Yahoo resource to get the stock pricing. The source needs to be saved in the file in the classes\com\jguru directory under the JSWDK installation directory. From there, compile it with the javac compiler from the JSDK.


Exhibit 3
Your first JSP page

Once you've created the two JSP files, as well as created the JavaBean source file and compiled it, you can load up the quote.jsp file to see the results from http://localhost:8080/quote.jsp, assuming you haven't changed the JSWDK installation to use a different port. The page can definitely be prettied up, but it does what it needs to do functionally and is a good demonstration of JSP's capabilities.

Editor's Picks

Free Newsletters, In your Inbox