JSP Tutorial
JSP Tutorial
Audience
This tutorial has been prepared for the beginners to help them understand basic
functionality of Java Server Pages (JSP) to develop your web applications. After completing
this tutorial you will find yourself at a moderate level of expertise in using JSP from where
you can take yourself to next levels.
Prerequisites
We assume you have little knowledge of how web applications work over HTTP, what is
web server and what is web browsers. It will be great if you have some knowledge of web
application development using any programming language.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
i
JSP
Table of Contents
About the Tutorial .................................................................................................................................... i
Audience .................................................................................................................................................. i
Prerequisites ............................................................................................................................................ i
ii
JSP
Common Attributes............................................................................................................................... 34
iv
JSP
v
JSP
vi
JSP
vii
JSP
viii
JSP
ix
JSP
x
JSP ─ OVERVIEW JSP
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.
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.
11
JSP
Advantages of JSP
Following is the list of other advantages of using JSP over other technologies:
vs. 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.
What is Next?
I would take you step by step to set up your environment to start with JSP. I'm assuming you
have good hands-on with Java Programming to proceed with learning JSP.
If you are not aware of Java Programming Language, then we would recommend you go
through our Java Tutorial to understand Java Programming.
12
JSP ─ ENVIRONMENT SETUP JSP
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:
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
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.
13
JSP
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:
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/.
14
JSP
Further information about configuring and running Tomcat can be found in the documentation
included here, as well as on the Tomcat web site: http://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
or
15
JSP
/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh
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%
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
16
JSP ─ ARCHITECTURE JSP
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.
17
JSP
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. This output is
further passed on to the web server by the servlet engine inside an HTTP response.
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
18
JSP ─ LIFECYCLE JSP
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.
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:
19
JSP
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.
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:
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.
20
JSP
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.
21
JSP ─ SYNTAX JSP
In this chapter, we will discuss Syntax in JSP. We will understand the basic use of simple
syntax (i.e., elements) involved with JSP development.
Elements of JSP
The elements of JSP have been described below:
The Scriptlet
A scriptlet can contain any number of JAVA language statements, variable or method
declarations, or expressions that are valid in the page scripting language.
You can write the XML equivalent of the above syntax as follows:
<jsp:scriptlet>
code fragment
</jsp:scriptlet>
Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the
simple and first example for JSP:
<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>
22
JSP
Let us keep the above code in JSP file hello.jsp and put this file in C:\apache-tomcat-
7.0.2\webapps\ROOT directory. Browse through the same using URL
http://localhost:8080/hello.jsp. This would generate the following result:
JSP Declarations
A declaration declares one or more variables or methods that you can use in Java code later
in the JSP file. You must declare the variable or method before you use it in the JSP file.
You can write the XML equivalent of the above syntax as follows:
<jsp:declaration>
code fragment
</jsp:declaration>
JSP Expression
A JSP expression element contains a scripting language expression that is evaluated,
converted to a String, and inserted where the expression appears in the JSP file.
23
JSP
Because the value of an expression is converted to a String, you can use an expression within
a line of text, whether or not it is tagged with HTML, in a JSP file.
The expression element can contain any expression that is valid according to the Java
Language Specification but you cannot use a semicolon to end an expression.
You can write the XML equivalent of the above syntax as follows:
<jsp:expression>
expression
</jsp:expression>
<html>
<head><title>A Comment Test</title></head>
<body>
<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
</body>
</html>
JSP Comments
JSP comment marks the text or the statements that the JSP container should ignore. A JSP
comment is useful when you want to hide or "comment out", a part of your JSP page.
24
JSP
<html>
<head><title>A Comment Test</title></head>
<body>
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
</body>
</html>
There are a small number of special constructs you can use in various cases to insert
comments or characters that would otherwise be treated specially. Here's a summary:
Syntax Purpose
25
JSP
JSP Directives
A JSP directive affects the overall structure of the servlet class. It usually has the following
form:
Directive Description
<%@ include ... %> Includes a file during the translation phase.
JSP Actions
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You
can dynamically insert a file, reuse JavaBeans components, forward the user to another page,
or generate HTML for the Java plugin.
There is only one syntax for the Action element, as it conforms to the XML standard:
Action elements are basically predefined functions. Following table lists out the available JSP
Actions:
Syntax Purpose
26
JSP
27
JSP
Objects Description
page This is simply a synonym for this, and is used to call the
methods defined by the translated servlet class.
28
JSP
We would explain JSP Implicit Objects in a separate chapter — JSP - Implicit Objects.
29
JSP
Control-Flow Statements
You can use all the APIs and building blocks of Java in your JSP programming including
decision-making statements, loops, etc.
Decision-Making Statements
The if...else block starts out like an ordinary Scriptlet, but the Scriptlet is closed at each line
with HTML text included between the Scriptlet tags.
Now look at the following switch...case block which has been written a bit differentlty
using out.println() and inside Scriptletas:
break;
case 1:
out.println("It\'s Monday.");
break;
case 2:
out.println("It\'s Tuesday.");
break;
case 3:
out.println("It\'s Wednesday.");
break;
case 4:
out.println("It\'s Thursday.");
break;
case 5:
out.println("It\'s Friday.");
break;
default:
out.println("It's Saturday.");
}
%>
</body>
</html>
Loop Statements
You can also use three basic types of looping blocks in Java: for, while,and do…while blocks
in your JSP programming.
<html>
<head><title>FOR LOOP Example</title></head>
<body>
<%for ( fontSize = 1; fontSize <= 3; fontSize++){ %>
<font color="green" size="<%= fontSize %>">
JSP Tutorial
</font><br />
<%}%>
</body>
</html>
</font><br />
<%fontSize++;%>
<%}%>
</body>
</html>
JSP Operators
JSP supports all the logical and arithmetic operators supported by Java. Following table lists
out all the operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom.
33
JSP
JSP Literals
The JSP expression language defines the following literals:
Integer: as in Java
String: with single and double quotes; " is escaped as \", ' is escaped as \', and \ is
escaped as \\.
Null: null
34
JSP ─ DIRECTIVES JSP
In this chapter, we will discuss Directives in JSP. These directives provide directions and
instructions to the container, telling it how to handle certain aspects of the JSP processing.
A JSP directive affects the overall structure of the servlet class. It usually has the following
form:
Directives can have a number of attributes which you can list down as key-value pairs and
separated by commas.
The blanks between the @ symbol and the directive name, and between the last attribute and
the closing %>, are optional.
Directive Description
<%@ include ... %> Includes a file during the translation phase.
<%@ taglib ... %> Declares a tag library, containing custom actions, used in the
page
You can write the XML equivalent of the above syntax as follows:
35
JSP
Attributes
Following table lists out the attributes associated with page directive:
Attribute Purpose
36
JSP
Check for more details related to all the above attributes at Page Directive.
You can write the XML equivalent of the above syntax as follows:
Attributes
Following table lists out the attributes associated with the page directive:
Attribute Purpose
37
JSP
You may code a value of "none" to specify no buffering so that the servlet output is
immediately directed to the response object or you may code a maximum buffer size in
kilobytes, which directs the servlet to write to the buffer before writing to the response object.
To direct the servlet to write the output directly to the response output object, use the
following:
Use the following to direct the servlet to write the output to a buffer of size not less than 8
kilobytes:
The autoFlush attribute specifies whether buffered output should be flushed automatically
when the buffer is filled, or whether an exception should be raised to indicate the buffer
overflow.
A value of true (default) indicates automatic buffer flushing and a value of false throws an
exception.
The following directive causes the servlet to throw an exception when the servlet's output
buffer is full:
This directive causes the servlet to flush the output buffer when full:
Usually, the buffer and the autoFlush attributes are coded on a single page directive as
follows:
If you want to write out XML from your JSP, use the following page directive:
The following statement directs the browser to render the generated page as HTML:
The following directive sets the content type as a Microsoft Word document:
You can also specify the character encoding for the response. For example, if you wanted to
specify that the resulting page that is returned to the browser uses ISO Latin 1, you can use
the following page directive:
39
JSP
The following directive displays MyErrorPage.jsp when all uncaught exceptions are thrown:
The value of isErrorPage is either true or false. The default value of the isErrorPage attribute
is false.
For example, the handleError.jsp sets the isErrorPage option to true because it is supposed
to handle errors:
For example, the following directive directs the JSP translator to generate the servlet such
that the servlet extends somePackage.SomeClass:
To import multiple packages, you can specify them separated by comma as follows:
40
JSP
For example, because you usually use Java as the scripting language, your language option
looks like this:
Following directive allows the JSP page to use any of the builtin object session methods such
as session.getCreationTime() or session.getLastAccessTime():
The default value of the attribute is true, meaning that expressions, ${...}, are evaluated as
dictated by the JSP specification. If the attribute is set to false, then expressions are not
evaluated but rather treated as static text.
41
JSP
The default value (true) enables scriptlets, expressions, and declarations. If the attribute's
value is set to false, a translation-time error will be raised if the JSP uses any scriptlets,
expressions (non-EL), or declarations.
The attribute’s value can be set to false if you want to restrict the usage of scriptlets,
expressions (non-EL), or declarations:
The filename in the include directive is actually a relative URL. If you just specify a filename
with no associated path, the JSP compiler assumes that the file is in the same directory as
your JSP.
You can write the XML equivalent of the above syntax as follows:
For more details related to include directive, check the Include Directive.
42
JSP
The filename in the include directive is actually a relative URL. If you just specify a filename
with no associated path, the JSP compiler assumes that the file is in the same directory as
your JSP.
You can write the XML equivalent of the above syntax as follows:
Example
A good example of the include directive is including a common header and footer with
multiple pages of content.
Let us define following three files (a) header.jps, (b)footer.jsp, and (c)main.jsp as
follows:
<%!
int pageCount = 0;
void addCount() {
pageCount++;
}
%>
<% addCount(); %>
<html>
<head>
<title>The include Directive Example</title>
</head>
<body>
<center>
<h2>The include Directive Example</h2>
<p>This site has been visited <%= pageCount %> times.</p>
</center>
<br/><br/>
43
JSP
Let us now keep all these files in the root directory and try to access main.jsp. You will
receive the following output:
Refresh main.jsp and you will find that the page hit counter keeps increasing.
You can design your webpages based on your creative instincts; it is recommended you keep
the dynamic parts of your website in separate files and then include them in the main file.
This makes it easy when you need to change a part of your webpage.
44
JSP
The taglib directive declares that your JSP page uses a set of custom tags, identifies the
location of the library, and provides means for identifying the custom tags in your JSP page.
Here, the uri attribute value resolves to a location the container understands and
the prefix attribute informs a container what bits of markup are custom actions.
You can write the XML equivalent of the above syntax as follows:
For more details related to the taglib directive, check the Taglib Directive.
The taglib directive declares that your JSP page uses a set of custom tags, identifies the
location of the library, and provides a means for identifying the custom tags in your JSP page.
Where the uri attribute value resolves to a location the container understands and
the prefix attribute informs a container what bits of markup are custom actions.
You can write the XML equivalent of the above syntax as follows:
When you use a custom tag, it is typically of the form <prefix:tagname>. The prefix is the
same as the prefix you specify in the taglib directive, and the tagname is the name of a tag
implemented in the tag library.
Example
For example, suppose the custlib tag library contains a tag called hello. If you wanted to
use the hello tag with a prefix of mytag, your tag would be <mytag:hello> and it will be
used in your JSP file as follows:
45
JSP
<body>
<mytag:hello/>
</body>
</html>
We can call another piece of code using <mytag:hello>. We will see how to develop our
custom tags and how to use them in JSP - Custom Tags tutorial.
46
JSP
47