You are on page 1of 34

CURRICULUM REPORT

ON

WEB DEVELOPMENT USING JSP

by

Shreyanshi Vashistha (1501410098)

Submitted to the Department of Computer Science

in partial fulfillment of the requirements

for the degree of

Bachelor of Technology

in

Computer Science

Department of Computer Science

SHRI RAM MURTI SMARAK COLLEGE OF ENGINEERING AND


TECHNOLOGY, BAREILLY
Dr. A.P.J. Abdul Kalam Technical University, U.P., Lucknow.

1
TABLE OF CONTENTS Page

CERTIFICATE ..................................................................................................... 3
ACKNOWLEDGEMENT .................................................................................... 4
INTRODUCTION ................................................................................................. 5
JSP ENVIRONMENT SETUP............................................................................... 7
JSP ARCHITECTURE........................................................................................... 10
JSP LIFECYCLE ................................................................................................... 12
JAVA WEB APPLICATION ................................................................................. 14
JAVA WEB DEVELOPMENT............................................................................... 16
WEB SEVICES........................................................................................................ 24
HOW JSP WEB PAGES WORKS........................................................................... 27
CONCLUSION.......................................................................................................... 34

2
CERTIFICATE

This is to certify that the Curriculum Report entitled Web Development Using JSP which is
submitted by Shreyanshi Vashistha (1501410098) is a record of the candidates own work
carried out by them under my supervision. The matter embodied in this work is original
and has not been submitted for the award of any other work or degree.

Mr. Manoj Kumar

Supervisor

3
ACKNOWLEDGEMENT

It gives us a great sense of pleasure to present the curriculum report of the B. Tech .We owe
special debt of gratitude to Professor Manoj Kumar, Computer Science, S.R.M.S.C.E.T, Bareilly
for his constant support and guidance throughout the course of our work. His sincerity,
thoroughness and perseverance have been a constant source of inspiration for us. It is only his
cognizant efforts that our endeavors have seen light of the day. Last but not the least, we
acknowledge our friends for their contribution in the completion of the project.

Shreyanshi Vashistha

1501410098

Date

4
INTRODUCTION

Java Server Pages (JSP) is a server-side programming technology that enables the
creation of dynamic, platform-independent method for building Web-based applications.
JSP have access to the entire family of Java APIs, including the JDBC API to access
enterprise databases. This tutorial will teach you how to use Java Server Pages to develop
your web applications in simple and easy steps.

What is JavaServer Pages?


JavaServer Pages (JSP) is a technology for developing Webpages that supports dynamic content.
This helps developers insert java code in HTML pages by making use of special JSP tags, most
of which start with <% and end with %>.

A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a
user interface for a Java web application. Web developers write JSPs as text files that combine
HTML or XHTML code, XML elements, and embedded JSP actions and commands.

Using JSP, you can collect input from users through Webpage forms, present records from a
database or another source, and create Webpages dynamically.

JSP tags can be used for a variety of purposes, such as retrieving information from a database or
registering user preferences, accessing JavaBeans components, passing control between pages,
and sharing information between requests, pages etc.

Why Use JSP?


JavaServer Pages often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But JSP offers several advantages in comparison with the CGI.

 Performance is significantly better because JSP allows embedding Dynamic Elements in


HTML Pages itself instead of having separate CGI files.
 JSP are always compiled before they are processed by the server unlike CGI/Perl which
requires the server to load an interpreter and the target script each time the page is
requested.
 JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has
access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP, etc.
 JSP pages can be used in combination with servlets that handle the business logic, the
model supported by Java servlet template engines.

Finally, JSP is an integral part of Java EE, a complete platform for enterprise class applications.
This means that JSP can play a part in the simplest applications to the most complex and
demanding.

5
Advantages of JSP
Following table lists out the other advantages of using JSP over other technologies −

Active Server Pages (ASP)

The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual Basic or
other MS specific language, so it is more powerful and easier to use. Second, it is portable to
other operating systems and non-Microsoft Web servers.

Pure Servlets

It is more convenient to write (and to modify!) regular HTML than to have plenty of println
statements that generate the HTML.

Server-Side Includes (SSI)

SSI is really only intended for simple inclusions, not for "real" programs that use form data,
make database connections, and the like.

JavaScript

JavaScript can generate HTML dynamically on the client but can hardly interact with the web
server to perform complex tasks like database access and image processing etc.

Static HTML

Regular HTML, of course, cannot contain dynamic information.

6
JSP - Environment Setup

A development environment is where you would develop your JSP programs, test them and
finally run them.

This tutorial will guide you to setup your JSP development environment which involves the
following steps −

Setting up Java Development Kit


This step involves downloading an implementation of the Java Software Development Kit (SDK)
and setting up the PATH environment variable appropriately.

You can download SDK from Oracle's Java site − Java SE Downloads.

Once you download your Java implementation, follow the given instructions to install and
configure the setup. Finally set the PATH and JAVA_HOME environment variables to refer to
the directory that contains java and javac, typically java_install_dir/bin and java_install_dir
respectively.

If you are running Windows and install the SDK in C:\jdk1.5.0_20, you need to add the
following line in your C:\autoexec.bat file.

set PATH = C:\jdk1.5.0_20\bin;%PATH%


set JAVA_HOME = C:\jdk1.5.0_20

Alternatively, on Windows NT/2000/XP, you can also right-click on My Computer, select


Properties, then Advanced, followed by Environment Variables. Then, you would update the
PATH value and press the OK button.

On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C
shell, you will put the following into your .cshrc file.

setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH


setenv JAVA_HOME /usr/local/jdk1.5.0_20

Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder,
Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that
the IDE knows where you installed Java.

Setting up Web Server: Tomcat

A number of Web Servers that support JavaServer Pages and Servlets development are available
in the market. Some web servers can be downloaded for free and Tomcat is one of them.

7
Apache Tomcat is an open source software implementation of the JavaServer Pages and Servlet
technologies and can act as a standalone server for testing JSP and Servlets, and can be
integrated with the Apache Web Server. Here are the steps to set up Tomcat on your machine −

 Download the latest version of Tomcat from https://tomcat.apache.org/.


 Once you downloaded the installation, unpack the binary distribution into a convenient
location. For example, in C:\apache-tomcat-5.5.29 on windows, or /usr/local/apache-
tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME environment variable
pointing to these locations.

Tomcat can be started by executing the following commands on the Windows machine −

%CATALINA_HOME%\bin\startup.bat

or

C:\apache-tomcat-5.5.29\bin\startup.bat

Tomcat can be started by executing the following commands on the Unix (Solaris, Linux, etc.)
machine −

$CATALINA_HOME/bin/startup.sh

or

/usr/local/apache-tomcat-5.5.29/bin/startup.sh

After a successful startup, the default web-applications included with Tomcat will be available
by visiting http://localhost:8080/.

Upon execution, you will receive the following output −

Further information about configuring and running Tomcat can be found in the documentation
included here, as well as on the Tomcat web site − https://tomcat.apache.org/.

Tomcat can be stopped by executing the following commands on the Windows machine −

%CATALINA_HOME%\bin\shutdown
or

C:\apache-tomcat-5.5.29\bin\shutdown

Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.)
machine −

$CATALINA_HOME/bin/shutdown.sh

8
Setting up CLASSPATH
Since servlets are not part of the Java Platform, Standard Edition, you must identify the servlet
classes to the compiler.

If you are running Windows, you need to put the following lines in your C:\autoexec.bat file.

set CATALINA = C:\apache-tomcat-5.5.29


set CLASSPATH = %CATALINA%\common\lib\jsp-api.jar;%CLASSPATH%

Alternatively, on Windows NT/2000/XP, you can also right-click on My Computer, select


Properties, then Advanced, then Environment Variables. Then, you would update the
CLASSPATH value and press the OK button.

On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the following lines
into your .cshrc file.

setenv CATALINA = /usr/local/apache-tomcat-5.5.29


setenv CLASSPATH $CATALINA/common/lib/jsp-api.jar:$CLASSPATH

NOTE − Assuming that your development directory is C:\JSPDev (Windows) or /usr/JSPDev


(Unix), then you would need to add these directories as well in CLASSPATH.

9
JSP - Architecture

The web server needs a JSP engine, i.e, a container to process JSP pages. The JSP container is
responsible for intercepting requests for JSP pages. This tutorial makes use of Apache which has
built-in JSP container to support JSP pages development.

A JSP container works with the Web server to provide the runtime environment and other
services a JSP needs. It knows how to understand the special elements that are part of JSPs.

Following diagram shows the position of JSP container and JSP files in a Web application.

JSP Processing
The following steps explain how the web server creates the Webpage using JSP −

 As with a normal page, your browser sends an HTTP request to the web server.
 The web server recognizes that the HTTP request is for a JSP page and forwards it to a
JSP engine. This is done by using the URL or JSP page which ends with .jsp instead of
.html.
 The JSP engine loads the JSP page from disk and converts it into a servlet content. This
conversion is very simple in which all template text is converted to println( ) statements
and all JSP elements are converted to Java code. This code implements the corresponding
dynamic behavior of the page.
 The JSP engine compiles the servlet into an executable class and forwards the original
request to a servlet engine.
 A part of the web server called the servlet engine loads the Servlet class and executes it.
During execution, the servlet produces an output in HTML format. The output is furthur
passed on to the web server by the servlet engine inside an HTTP response.

10
 The web server forwards the HTTP response to your browser in terms of static HTML
content.
 Finally, the web browser handles the dynamically-generated HTML page inside the
HTTP response exactly as if it were a static page.

All the above mentioned steps can be seen in the following diagram −

Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and
whether the modification date on the JSP is older than the servlet. If the JSP is older than its
generated servlet, the JSP container assumes that the JSP hasn't changed and that the generated
servlet still matches the JSP's contents. This makes the process more efficient than with the other
scripting languages (such as PHP) and therefore faster.

So in a way, a JSP page is really just another way to write a servlet without having to be a Java
programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular
servlet.

11
JSP - Lifecycle

In this chapter, we will discuss the lifecycle of JSP. The key to understanding the low-level
functionality of JSP is to understand the simple life cycle they follow.

A JSP life cycle is defined as the process from its creation till the destruction. This is similar to a
servlet life cycle with an additional step which is required to compile a JSP into servlet.

Paths Followed By JSP


The following are the paths followed by a JSP −

 Compilation
 Initialization
 Execution
 Cleanup

The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. The four
phases have been described below −

JSP Compilation

When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the
page. If the page has never been compiled, or if the JSP has been modified since it was last
compiled, the JSP engine compiles the page.

12
The compilation process involves three steps −

 Parsing the JSP.


 Turning the JSP into a servlet.
 Compiling the servlet.

JSP Initialization

When a container loads a JSP it invokes the jspInit() method before servicing any requests. If
you need to perform JSP-specific initialization, override the jspInit() method −

public void jspInit(){


// Initialization code...
}

Typically, initialization is performed only once and as with the servlet init method, you generally
initialize database connections, open files, and create lookup tables in the jspInit method.

JSP Execution

This phase of the JSP life cycle represents all interactions with requests until the JSP is
destroyed.

Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine
invokes the _jspService() method in the JSP.

The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its


parameters as follows −

void _jspService(HttpServletRequest request, HttpServletResponse response) {


// Service handling code...
}

The _jspService() method of a JSP is invoked on request basis. This is responsible for generating
the response for that request and this method is also responsible for generating responses to all
seven of the HTTP methods, i.e, GET, POST, DELETE, etc.

JSP Cleanup
The destruction phase of the JSP life cycle represents when a JSP is being removed from use by
a container.

The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override
jspDestroy when you need to perform any cleanup, such as releasing database connections or
closing open files.

13
Java Web Application

The aim of this article is to provide basic details of different components in Web Application and
how can we use Servlet and JSP to create our first java web application.

Web Server and Client

Web Server is a software that can process the client request and send the response back to the
client. For example, Apache is one of the most widely used web server. Web Server runs on
some physical machine and listens to client request on specific port.

A web client is a software that helps in communicating with the server. Some of the most widely
used web clients are Firefox, Google Chrome, Safari etc. When we request something from
server (through URL), web client takes care of creating a request and sending it to server and
then parsing the server response and present it to the user.

HTML and HTTP

Web Server and Web Client are two separate softwares, so there should be some common
language for communication. HTML is the common language between server and client and
stands for HyperText Markup Language.

Web server and client needs a common communication protocol, HTTP (HyperText Transfer
Protocol) is the communication protocol between server and client. HTTP runs on top of TCP/IP
communication protocol.

Some of the important parts of HTTP Request are:

 HTTP Method – action to be performed, usually GET, POST, PUT etc.


 URL – Page to access
 Form Parameters – similar to arguments in a java method, for example user,password
details from login page.

Some of the important parts of HTTP Response are:

 Status Code – an integer to indicate whether the request was success or not. Some of the
well known status codes are 200 for success, 404 for Not Found and 403 for Access
Forbidden.
 Content Type – text, html, image, pdf etc. Also known as MIME type
 Content – actual data that is rendered by client and shown to user.
 MIME Type or Content Type: If you see above sample HTTP response header, it
contains tag “Content-Type”. It’s also called MIME type and server sends it to client to
let them know the kind of data it’s sending. It helps client in rendering the data for user.
Some of the mostly used mime types are text/html, text/xml, application/xml etc.

14
 Understanding URL
 URL is acronym of Universal Resource Locator and it’s used to locate the server and
resource. Every resource on the web has it’s own unique address. Let’s see parts of URL
with an example.
 http://localhost:8080/FirstServletProject/jsps/hello.jsp
 http:// – This is the first part of URL and provides the communication protocol to be
used in server-client communication.
 localhost – The unique address of the server, most of the times it’s the hostname of the
server that maps to unique IP address. Sometimes multiple hostnames point to same IP
addresses and web server virtual host takes care of sending request to the particular server
instance.
 8080 – This is the port on which server is listening, it’s optional and if we don’t provide
it in URL then request goes to the default port of the protocol. Port numbers 0 to 1023 are
reserved ports for well known services, for example 80 for HTTP, 443 for HTTPS, 21 for
FTP etc.
 FirstServletProject/jsps/hello.jsp – Resource requested from server. It can be static
html, pdf, JSP, servlets, PHP etc.
 Why we need Servlet and JSPs?
 Web servers are good for static contents HTML pages but they don’t know how to
generate dynamic content or how to save data into databases, so we need another tool that
we can use to generate dynamic content. There are several programming languages for
dynamic content like PHP, Python, Ruby on Rails, Java Servlets and JSPs.
 Java Servlet and JSPs are server side technologies to extend the capability of web servers
by providing support for dynamic response and data persistence.

15
Java Web Development

First Web Application with Servlet and JSP

We will use “Eclipse IDE for Java EE Developers” for creating our first servlet application.
Since servlet is a server side technology, we will need a web container that supports Servlet
technology, so we will use Apache Tomcat server. It’s very easy to setup and I am leaving
that part to yourself.

For ease of development, we can add configure Tomcat with Eclipse, it helps in easy
deployment and running applications.

Go to Eclipse Preference and select Server Runtime Environments and select the version of
your tomcat server, mine is Tomcat 7.

Provide the apache tomcat directory location and JRE information to add the runtime
environment.

Now go to the Servers view and create a new server like below image pointing to the above
added runtime environment.

16
Note: If Servers tab is not visible, then you can select Window > Show View > Servers so
that it will be visible in Eclipse window. Try stopping and starting server to make sure it’s
working fine. If you have already started the server from terminal, then you will have to stop
if from terminal and then start it from Eclipse else it won’t work perfectly.

Now we are ready with our setup to create first servlet and run it on tomcat server.

Select File > New > Dynamic Web Project and use below image to provide runtime as the
server we added in last step and module version as 3.0 to create our servlet using Servlet 3.0
specs.

You can directly click Finish button to create the project or you can click on Next buttons to
check for other options.

17
Now select File > New > Servlet and use below image to create our first servlet. Again we
can click finish or we can check other options through next button.

When we click on Finish button, it generates our Servlet skeleton code, so we don’t need to
type in all the different methods and imports in servlet and saves us time.

Now we will add some HTML with dynamic data code in doGet() method that will be
invoked for HTTP GET request. Our first servlet looks like below.

Copy

Before Servlet 3, we need to provide the url pattern information in web application
deployment descriptor but servlet 3.0 uses java annotations that is easy to understand and
chances of errors are less.

Now chose Run > Run on Server option from servlet editor window and use below images
for the options.

18
19
After clicking finish, browser will open in Eclipse and we get following HTML page.

You can refresh it to check that Date is dynamic and keeps on changing, you can open it
outside of Eclipse also in any other browser.

So servlet is used to generate HTML and send it in response, if you will look into the doGet()
implementation, we are actually creating an HTML document as writing it in response
PrintWriter object and we are adding dynamic information where we need it.

It’s good for start but if the response is huge with lot of dynamic data, it’s error prone and
hard to read and maintain. This is the primary reason for introduction of JSPs.

20
JSP is also server side technology and it’s like HTML with additional features to add
dynamic content where we need it.
JSPs are good for presentation because it’s easy to write because it’s like HTML. Here is our
first JSP program that does the same thing like above servlet.

If we run above JSP, we get output like below image.

The final project hierarchy looks like below image in Eclipse.

We will look into Servlets and JSPs in more detail in future posts but before concluding this
post, we should have good understanding of some of the aspects of java web applications.

Web Container

Tomcat is a web container, when a request is made from Client to web server, it passes the
request to web container and it’s web container job to find the correct resource to handle the

21
request (servlet or JSP) and then use the response from the resource to generate the response
and provide it to web server. Then web server sends the response back to the client.

When web container gets the request and if it’s for servlet then container creates two Objects
HTTPServletRequest and HTTPServletResponse. Then it finds the correct servlet based on
the URL and creates a thread for the request. Then it invokes the servlet service() method and
based on the HTTP method service() method invokes doGet() or doPost() methods. Servlet
methods generate the dynamic page and write it to response. Once servlet thread is complete,
container converts the response to HTTP response and send it back to client.

Some of the important work done by web container are:

Communication Support – Container provides easy way of communication between web


server and the servlets and JSPs. Because of container, we don’t need to build a server socket
to listen for any request from web server, parse the request and generate response. All these
important and complex tasks are done by container and all we need to focus is on our
business logic for our applications.

Lifecycle and Resource Management – Container takes care of managing the life cycle of
servlet. Container takes care of loading the servlets into memory, initializing servlets,
invoking servlet methods and destroying them. Container also provides utility like JNDI for
resource pooling and management.

Multithreading Support – Container creates new thread for every request to the servlet and
when it’s processed the thread dies. So servlets are not initialized for each request and saves
time and memory.

JSP Support – JSPs doesn’t look like normal java classes and web container provides
support for JSP. Every JSP in the application is compiled by container and converted to
Servlet and then container manages them like other servlets.

Miscellaneous Task – Web container manages the resource pool, does memory
optimizations, run garbage collector, provides security configurations, support for multiple
applications, hot deployment and several other tasks behind the scene that makes our life
easier.

Web Application Directory Structure

Java Web Applications are packaged as Web Archive (WAR) and it has a defined structure.
You can export above dynamic web project as WAR file and unzip it to check the hierarchy.
It will be something like below image.

22
Deployment Descriptor

web.xml file is the deployment descriptor of the web application and contains mapping for
servlets (prior to 3.0), welcome pages, security configurations, session timeout settings etc.

Thats all for the java web application startup tutorial, we will explore Servlets and JSPs more
in future posts.

23
Web Services

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. JavaServer Pages
(JSP) are here.

JSP pages 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's and tomorrow's market. This series begins with this article, which
explains the concepts and benefits of JSP technology, and then shows you how to utilize this
exciting technology, and how to create reusable components for handling forms.

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 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.

JSP pages 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.

24
JavaServer Pages (JSP)

The JSP technology is 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
Java 2 Enterprise Edition (J2EE) specification. Many of the commercially available application
servers (such as BEA WebLogic, IBM WebSphere, Live JRun, Orion, and so on) already support
JSP technology.

JSP versus 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:

 ASP pages are written in VBScript and JSP pages are written in the Java programming
language. Therefore, JSP pages are platform-independent and ASP pages are not.
 JSP pages use JavaBeans technology as the component architecture and ASP pages 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 ASP pages are cached, they are always interpreted. By
contrast, JSP pages are compiled into Java servlets and loaded into memory the first time
they are called, and executed for all subsequent calls. This gives JSP pages aspeed and
scalability advantage over ASP pages.
 Extensible Tags : JSP pages 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 JSP pages tag syntax. You cannot do this with ASP pages.
 Freedom of Choice : Unless you install Chili!Soft ASP, ASP pages work only with
Microsoft IIS and Personal Web Server. Using ASP pages requires a commitment to
Microsoft products, while JSP pages do not tie you to any specific web server or
operating system. JSP pages are becoming a widely supported standard.

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.

25
To configure Tomcat:

 Set the environment variable JAVA_HOME to point to the root directory of your Java 2
Standard Edition (J2SE) installation.
 Set the TOMCAT_HOME environment variable to point to the root directory of your Tomcat
installation.
 To start Tomcat, use TOMCAT_HOME/bin/startup.bat for windows or startup.sh for
UNIX.
By default, it will start listening on port 8080.
 Save your .jsp files in TOMCAT_HOME/webapps/examples/jsp and your JavaBeans
classes in TOMCAT_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
DOS window to a value greater than 3200 OR edit the config.sys file and add the following line:
SHELL=c:\PATHTO\command.com /E:4096 /P.

26
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 scriptlet, and the %> tag identifies the end of a scriptlet. When date.jsp is
requested from a web browser.

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.

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.

27
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:

28
 Use <% ... %> to handle declarations, expressions, or any other type of valid snippet of
code. Sample 1 above is an example.
 Use the page directive as in <%@page ... %> to define the scripting language. Also, it
can be used to specify import statements. 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 a String. For example:
<%= a+b %> or <%= new java.util.Date() %>.
 Use the include directive 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 ecommerce 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"

29
ACTION="/developer/technicalArticles/xml/WebAppDev/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.

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

30
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:

1. Your bean class must provide a constructor with no arguments so it can be created using
Beans.instantiate.
2. Your bean class must support persistence by implementing the interface Serializable
or Externalizable.

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;
}

31
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>

32
</HEAD>
<BODY BGCOLOR="#ffffcc">
<% if (request.getParameter("name")==null
&& request.getParameter("email") == null) { %>
<CENTER>
<H2>User Info Request Form </H2>
<form method="GET"
action="/developer/technicalArticles/xml/WebAppDev/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>

33
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 next article will 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 JSP pages have XML support built right into them in the form of JSP
custom tag libraries. Stay tuned for more information on this in the next article in this series.

34

You might also like