Java Development News:
Web Application Development with JSP and XML: Part I Fast Track JSP
By Qusay H. Mahmoud
01 May 2001 | TheServerSide.com
If you have had the opportunity to build Web applications using technologies such as Common Gateway Interface (CGI) and servlets, you are accustomed to the idea of writing a program to generate the whole page (the static and the dynamic part) using that same program. If you are looking for a solution in which you can separate the two parts, look no further. JavaServerTMPages (JSPTM) are here.
JSPs allow you to separate front-end presentation from business logic (middle and back-end tiers). It is a great Rapid Application Development (RAD) approach to Web applications. This series of articles provides a hands-on tutorial explaining how to develop modern Web applications for today
The Dynamic Web
The Web has evolved from a network-based hypermedia distributed information system offering static information to a marketplace for selling and buying goods and services. The increasingly sophisticated applications to enable this marketplace require a technology for presenting dynamic information.
First generation solutions included CGI, which is a mechanism for running external programs through a Web server. The problem with CGI scripts is scalability; a new process is created for every request.
Second generation solutions included web server vendors providing plug-ins and APIs for their servers. The problem is that their solutions were specific to their server products. For example, Microsoft provided Active Server Pages (ASP) that made it easier to create dynamic content. However, their solution only worked with Microsoft IIS or Personal Web Server. Therefore, if you wanted to use ASP you had to commit yourself to Microsoft products and you would not be enjoying the freedom of selecting your favorite web server and operating system!
Another second generation technology that is quite popular in enterprise computing is Java servlets. Servlets make it easier to write server-side applications using Java technology. The problem with either CGI or servlets, however, is that you have to follow the write, compile, and deploy life cycle.
JSPs are a third generation solution that can be combined easily with some second generation solutions, creating dynamic content, and making it easier and faster to build Web-based applications that work with a variety of other technologies: web servers, web browsers, application servers and other development tools.
JavaServer Pages (JSP)
JSPs are an open, freely available specification developed by Sun Microsystems as an alternative to Microsoft's Active Server Pages (ASP) technology, and a key component of the JavaTM2 Enterprise Edition (J2EETM) specification. Many of the commercially available application servers (such as BEA WebLogic, IBM WebSphere, Live JRun, Orion, and so on) already support JSP.
JSP vs. ASP
JSP and ASP deliver similar functionality. They both use tags to allow embedded code in an HTML page, session tracking, and database connection. Some of the trivial differences are:
- ASPs are written in VBScript and JSPs are written in Java. Therefore, JSPs are platform-independent and ASPs are not.
- JSPs use JavaBeansTMtechnology as the component architecture and ASPs use ActiveX components.
Beyond these trivial differences, there are a number of important differences that may help you in choosing a technology for your organization:
- Speed and Scalability: Although ASPs are cached, they are always interpreted. By contrast, JSPs are compiled into Java servlets and loaded into memory the first time they are called, and executed for all subsequent calls. This gives JSPs speed and scalability advantage over ASPs.
- Extensible Tags: JSPs have an advanced feature known as extensible tags. This mechanism enables developers to create custom tags. In other words, extensible tags allow you to extend the JSPs tag syntax. You cannot do this with ASPs.
- Freedom of Choice: Unless you install Chili!Soft ASP, ASPs work only with Microsoft IIS and Personal Web Server. Using ASPs requires a commitment to Microsoft products, while JSPs do not tie you to any specific web server or operating system. JSPs are becoming a widely supported standard.
For a more detailed comparison between JSPs and ASPs, see Comparing JSP and ASP.
Software Environment
To run JSP pages, you need a web server with a web container that conforms to JSP and servlet specifications. The web container executes on the web server and manages the execution of all JSP pages and servlets running on that web server. Tomcat 3.2.1 is a complete reference implementation for the Java Servlet 2.2 and JSP 1.1 specifications. Download and install binary versions of Tomcat.
To configure Tomcat:
- Set
the environment variable
JAVA_HOMEto point to the root directory of your JavaTM2 Standard Edition (J2SETM) installation. - Set
the
TOMCAT_HOMEenvironment variable to point to the root directory of your Tomcat installation. - To
start Tomcat, use
TOMCAT_HOME/bin/startup.batfor windows orstartup.shfor UNIX.
By default, it will start listening on port 8080. - Save
your
.jspfiles inTOMCAT_HOME/webapps/examples/jspand your JavaBeans classes inTOMCAT_HOME/webapps/examples/web-inf/classes.
Note:
If you work under Windows, you may get an Out of space environment error
when you try to start Tomcat. There are two ways to fix this: either change the
initial memory setting of the DOES window to a value greater than 3200 OR edit
the config.sys file and add the following line:
SHELL=c:PATHTOcommand.com /E:4096
How JSP Pages Work
A JSP page is basically a web page with traditional HTML and bits of Java code. The file extension of a JSP page is ".jsp" rather than ".html" or ".htm", and that tells the server that this page requires special handling that will be accomplished by a server extension or a plug-in. Here is a simple example:
Sample 1:date.jsp
<HTML>
<HEAD>
<TITLE>JSP Example</TITLE>
</HEAD>
<BODY BGCOLOR="ffffcc">
<CENTER>
<H2>Date and Time</H2>
<%java.util.Date today = new java.util.Date();
out.println("Today's date is: "+today);%>
</CENTER>
</BODY>
</HTML>
This example contains traditional HTML and some Java code. The tag
<%
identifies the beginning of a script, and the
%>
tag identifies the end of a script. When
date.jsp
is requested from a Web browser, you see something similar to Figure 1.
Figure 1: Requesting date.jsp
Behind the Scenes
When this page
(date.jsp)
is called, it will be compiled (by the JSP engine) into a Java servlet. At this
point the servlet is handled by the servlet engine just like any other servlet.
The servlet engine then loads the servlet class (using a class loader) and
executes it to create dynamic HTML to be sent to the browser, as shown in Figure
2. For this example, the servlet creates a
Date
object and writes it as a string to the
out
object, which is an output stream to the browser.
Figure 2: Request/Response Flow when Calling a JSP
The next time the page is requested, the JSP engine executes the already-loaded servlet unless the JSP page has changed, in which case it is automatically recompiled into a servlet and executed.
Scripting Elements
In the
date.jsp
example the full
Date
class name is used including the package name, which may become tedious. If you
want to create an instance of
Date
simply by using:
Date
today = new Date();
without having to specify the full class path
use the
page
directive as follows:
Sample 2:date2.jsp
<%@page import="java.util.*" %>
<HTML>
<HEAD>
<TITLE>JSP Example</TITLE>
</HEAD>
<BODY BGCOLOR="ffffcc">
<CENTER>
<H2>Date and Time</H2>
<%
java.util.Date today = new java.util.Date();
out.println("Today's date is: "+today);
%>
</CENTER>
</BODY>
</HTML>
Yet, another way of doing the same thing using the
<%=
tag is by writing:
Sample 3:date3.jsp
<%@page import="java.util.*" %>
<HTML>
<HEAD>
<TITLE>JSP Example</TITLE>
</HEAD>
<BODY BGCOLOR="#ffffcc">
<CENTER>
<H2>Date and Time</H2>
Today's date is: <%= new Date() %>
</CENTER>
</BODY>
</HTML>
As you can see, the same thing can be accomplished using different tags and techniques. There are several JSP scripting elements. Here are some conventional rules that will help you use JSP scripting elements effectively:
- Use
<% ... %>to handle declarations, expressions, or any other type of valid snippet of code. Sample 1 above is an example. - Use
the
pagedirective as in<%@page ... %>to define the scripting language (the default is Java). Also, it can be used to specifyimportstatements. Here is an example:
<%@page language="java" import="java.util.*" %>. - Use
<%! .... %>to declare variables or methods. For example:
<%! int x = 10; double y = 2.0; %>. - Use
<%= ... %>to define an expression and cast the result as aString. For example:
<%= a+b %>or<%= new java.util.Date() %>. - Use
the
includedirective as in<%@ include ... %>to insert the contents of another file in the main JSP file. For example:
<%@include file="copyright.html" %>.
Handling Forms
One of the most common parts of e-commerce applications is an HTML form where
the user enters some information such as name and address. Using JSP, the form's
data (the information the user enters in the form) gets stored in the
request
object that is sent from the browser to the JSP container. The request is
processed and the result is sent through the
response
object back to the browser. These two objects are implicitly available to you.
To demonstrate how to handle HTML forms using JSP, here is an example form
with two fields: one for name and the other for email. As you can see, the HTML
form is defined in a JSP source file. The
request.getParameter
method is being used to retrieve data from the form into variables created using
JSP tags.
The
process.jsp
page prints either a form or the information provided by the user depending on
the values of the form's fields. If the form's values are
null
the form is displayed, otherwise, the information provided by the user is
displayed. Note that the form is created and being handled by code in the same
JSP file.
Sample 4:process.jsp
<HTML>
<HEAD>
<TITLE>Form Example</TITLE>
</HEAD>
<BODY BGCOLOR="#ffffcc">
<% if (request.getParameter("name")==null && request.getParameter("email") == null) { %>
<CENTER>
<H2>User Info Request Form</H2>
<FORM METHOD="GET" ACTION="process.jsp">
<P>
Your name: <input type="text" name="name" size=26>
<P>
Your email: <input type="text" name="email" size=26>
<P>
<input type="submit" value="Process">
</FORM>
</CENTER>
<% } else { %>
<%! String name, email; %>
<%
name = request.getParameter("name");
email = request.getParameter("email");
%>
<P>
<B>You have provided the following info</B>:
<P>
<B>Name</B>: <%= name %><P>
<B>Email</B>: <%= email %>
<% } %>
</BODY>
</HTML>
If
process.jsp
is requested from a web server, you see something similar to Figure 3.
Figure 3: process.jsp loaded
Enter your name and email and click on Process to submit the form for processing, and you see something similar to Figure 4.
Figure 4: Form is processed
Reusable Components
The above example form is simple in the sense that there is not much code involved. When more code is involved, then it is important not to mix business logic with front end presentation in the same file. Separating business logic from presentation permits changes to either side without affecting the other. However, production JSP code should be limited to front end presentation. So, how do you implement the business logic part?
That is where JavaBeans come in to play. This technology is a portable, platform-independent component model that lets developers write components and reuse them everywhere. In the context of JSP, JavaBeans contain business logic that returns data to a script on a JSP page, which in turn formats the data returned from the JavaBean component for display by the browser. A JSP page uses a JavaBean component by setting and getting the properties that it provides.
What are the Benefits
There are several benefits to using JavaBeans to augment JSP pages:
- Reusable components: different applications will be able to reuse the components.
- Separation of business logic and presentation logic: you can change the way data is displayed without affecting business logic.
- Protecting your intellectual property by keeping source code secure.
Example: Using JavaBeans with JSP
Now, let's see how to modify the
process.jsp
example above to use JavaBeans. In the above form these are two fields:
name
and
email
.
In JavaBeans, these are called properties. So, first you write a JavaBean
component with
setX
and
getX
methods, where X is the property name. For example, if you have
get and set methods:
setName
and
getName
then you have a property known as
name
.
Sample 5 shows a
FormBean
component.
Good components must be able to interoperate with other components from different vendors. Therefore, to achieve component reuse, there are two important rules (which are imposed by the JavaBeans architecture) to follow:
- Your
bean class must provide a constructor with no arguments so it can be created
using
Beans.instantiate. - Your
bean class must support persistence by implementing the interface
SerializableorExternalizable.
Sample 5:FormBean.java
package userinfo;
import java.io.*;
public class FormBean implements Serializable {
private String name;
private String email;
public FormBean() {
name = null;
email = null;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
}
In order to use the
FormBean
component in the JSP file, you need to instantiate the bean component. This is done using the
<jsp:useBean>
tag. The next line
<jsp:setProperty>
is executed when the bean is instantiated, and used to initialize the bean's properties. In this case, both properties (
name
and
email
) are set using a single statement. Alternatively, it is possible to set the properties one at a time, but first you need to retrieve the form's date. Here is an example of how you would set the
name
property:
<%! String yourname, youremail; %>
<% yourname = request.getParameter("name"); %>
<jsp:setProperty name="formbean" property="name" value="<%=yourname%>"/>
Once the properties have been initialized with data retrieved from the form, property values are retrieved for presentation using
<jsp:getProperty>
in the
else
part, as shown in Sample 6.
Sample 6:process2.jsp
<jsp:useBean id="formbean" class="userinfo.FormBean"/>
<jsp:setProperty name="formbean" property="*"/>
<HTML>
<HEAD>
<TITLE>Form Example</TITLE>
</HEAD>
<BODY BGCOLOR="#ffffcc">
<% if (request.getParameter("name")==null && request.getParameter("email") == null) { %>
<CENTER>
<H2>User Info Request Form </H2>
<form method="GET" action="process2.jsp">
<P>
Your name: <input type="text" name="name" size=27>
<p>
Your email: <input type="text" name="email" size=27>
<P>
<input type="submit" value="Process">
</FORM>
</CENTER>
<% } else { %>
<P>
<B>You have provided the following info</B>:
<P>
<B>Name</B>: <jsp:getProperty name="formbean" property="name"/>
<P>
<B>Email</B>: <jsp:getProperty name="formbean" property="email"/>
<% } %>
</BODY>
</HTML>
Conclusion
Developers interested in developing quality production web applications should familiarize themselves with technologies that are applicable not only for today's market but tomorrow's as well, namely JSP and XML. The J2EE BluePrints program from Sun provides a combination of design guidelines and sample applications to get you up to speed quickly. www.java.sun.com/j2ee/blueprints The next article will show how to create your own JSP tags; discuss the capabilities that the JSP technology provides that are ideally suited for working with XML; and show you how to effectively use JSP with XML. JSP and XML make an excellent combination for web applications that share information, because JSPs have XML support built right into them in the form of JSP tag libraries. Stay tuned for more information on this in the next article in this series.
For more information
ASP
Tomcat
Comparing JSP and ASP
About the Author
Qusay H. Mahmoud provides Java consulting and training services. Qusay has published dozens of articles on Java, and is the author of Distributed Programming with Java (Manning Publications, 1999).