Java Server Pages (JSP)
JSP stands for Java Server Pages. It is a server-side technology used for developing dynamic
web applica ons. It allows embedding Java code into HTML pages, which makes it easier to
generate dynamic content. JSP is considered an advanced form of Servlet technology
because internally every JSP is converted into a servlet before execu on. It is pla orm-
independent and helps in crea ng web-based applica ons efficiently.
JSP Processing (Working of JSP)
When a client requests a JSP page through a browser, the request is sent to the web server.
If the JSP file has already been compiled, the server directly returns the response.
Otherwise, the request is forwarded to the JSP engine.
The JSP engine first translates the JSP page into a servlet by conver ng all HTML content into
print statements and JSP elements into Java code. A er transla on, the servlet is compiled
into a class file. This compiled servlet is then executed by the servlet container, which
generates the output in the form of HTML. Finally, the web server sends this HTML response
back to the client’s browser.
Life Cycle of JSP
The life cycle of JSP begins from its crea on and con nues un l it is destroyed. It consists of
mul ple phases.
First, the JSP page is translated into a servlet source file. Then this servlet is compiled into a
class file. A er compila on, the class is loaded into memory. An object of the servlet is
created during instan a on.
Once the object is created, the ini aliza on phase starts in which the jspInit() method is
called by the container. This method is executed only once during the lifecycle.
A er ini aliza on, request processing takes place. The _jspService() method is invoked for
every client request and it generates the response.
Finally, when the JSP is no longer required, the jspDestroy() method is called to release
resources and perform cleanup.
JSP Implicit Objects
In JSP, there are nine implicit objects which are automa cally created by the web container.
These objects are available to all JSP pages without declara on and are used to handle
request, response, session and other opera ons easily.
1. out implicit object
The out object is of type JspWriter and is used to send output to the browser.
Example:
<%
[Link]("Hello World");
%>
2. request implicit object
The request object is of type H pServletRequest and is used to get data sent by the client
such as form values.
Example:
<%
String name = [Link]("name");
[Link]("Hello " + name);
%>
3. response implicit object
The response object is of type H pServletResponse and is used to send response or redirect
to another page.
Example:
<%
[Link]("[Link]");
%>
4. config implicit object
The config object is of type ServletConfig and is used to get ini aliza on parameters of a JSP.
Example:
<%
String driver = confi[Link]("dname");
[Link](driver);
%>
5. applica on implicit object
The applica on object is of type ServletContext and is used to store data for the en re
applica on.
Example:
<%
applica [Link] ribute("msg", "Welcome");
[Link](applica [Link] ribute("msg"));
%>
6. session implicit object
The session object is of type H pSession and is used to store user-specific data.
Example:
<%
[Link] ribute("user", "Raghav");
[Link]([Link] ribute("user"));
%>
7. pageContext implicit object
The pageContext object is used to access different scopes like page, request, session and
applica on.
Example:
<%
[Link] ribute("name", "Raghav");
[Link]([Link] ribute("name"));
%>
8. page implicit object
The page object represents the current JSP page (servlet object).
Example:
<%
[Link]([Link]());
%>
9. excep on implicit object
The excep on object is used in error pages to handle excep ons.
Example:
<%@ page isErrorPage="true" %>
<%
[Link](excep on);
%>
JSP Direc ves
JSP direc ves are special instruc ons given to the web container that control how a JSP page
is translated into a servlet. These direc ves are processed during the transla on phase and
do not generate any output. They affect the en re JSP page.
There are three types of JSP direc ves: page direc ve, include direc ve and taglib direc ve.
The general syntax of a direc ve is
<%@ direc ve a ribute="value" %>
1. Page Direc ve
The page direc ve is used to define global se ngs of a JSP page. It provides informa on
such as impor ng classes, se ng content type, error handling and controlling page behavior.
Syntax:
<%@ page a ribute="value" %>
Some important a ributes are as follows:
The import a ribute is used to import Java classes or packages so that they can be used in
JSP.
Example:
<%@ page import="java.u [Link]" %>
<html>
<body>
Today is: <%= new Date() %>
</body>
</html>
The contentType a ribute defines the MIME type of the response sent to the browser.
Example:
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<body>
Hello User
</body>
</html>
The buffer a ribute specifies the size of the output buffer.
Example:
<%@ page buffer="16kb" %>
<%= "Buffered Output" %>
The language a ribute specifies the scrip ng language used in JSP. By default it is Java.
Example:
<%@ page language="java" %>
The isELIgnored a ribute is used to enable or disable Expression Language.
Example:
<%@ page isELIgnored="true" %>
The isThreadSafe a ribute controls whether mul ple threads can access the JSP
simultaneously.
Example:
<%@ page isThreadSafe="false" %>
The errorPage a ribute specifies another JSP page to handle errors.
Example:
<%@ page errorPage="[Link]" %>
<%= 10/0 %>
The isErrorPage a ribute declares that a JSP page is an error page and allows use of
excep on object.
Example:
<%@ page isErrorPage="true" %>
Error occurred: <%= excep on %>
2. Include Direc ve
The include direc ve is used to include the content of another file during the transla on
phase. The included file becomes part of the current JSP page before compila on.
Syntax:
<%@ include file="filename" %>
Example:
<html>
<body>
<%@ include file="[Link]" %>
<h1>Welcome to Website</h1>
</body>
</html>
This is useful for including common components like header, footer or naviga on bar.
3. Taglib Direc ve
The taglib direc ve is used to declare tag libraries that contain custom tags. These tags
simplify JSP code and reduce the use of Java code inside JSP.
Syntax:
<%@ taglib uri="URI" prefix="prefix" %>
Example:
<%@ taglib uri="h p://[Link]/jsp/jstl/core" prefix="c" %>
<c:forEach var="i" begin="1" end="3">
<p>Number: ${i}</p>
</c:forEach>
This example uses JSTL tags instead of Java code.
JSP Ac on Tags
JSP ac on tags are special tags used to perform specific opera ons at request me. Unlike
direc ves, they are executed during run me and are used to control the flow between pages
and to work with JavaBeans.
These tags help in reducing Java code inside JSP and make the code more readable and
modular.
Some commonly used JSP ac on tags are jsp:forward, jsp:include, jsp:useBean,
jsp:setProperty, jsp:getProperty, jsp:param and jsp:plugin.
1. jsp:forward ac on tag
The jsp:forward tag is used to forward a request from one resource to another resource such
as JSP or HTML page. Once forwarded, the control is transferred and the remaining code of
the current page is not executed.
Syntax:
<jsp:forward page="url" />
Example:
<!-- [Link] -->
<html>
<body>
<h2>This is index page</h2>
<jsp:forward page="[Link]" />
</body>
</html>
<!-- [Link] -->
<html>
<body>
<%
[Link]("Welcome to next page");
%>
</body>
</html>
2. jsp:include ac on tag
The jsp:include tag is used to include another resource at run me. Unlike include direc ve, it
includes content dynamically.
Syntax:
<jsp:include page="url" />
Example:
<html>
<body>
<h2>Main Page</h2>
<jsp:include page="[Link]" />
</body>
</html>
3. jsp:useBean ac on tag
The jsp:useBean tag is used to create or locate a JavaBean object.
Syntax:
<jsp:useBean id="obj" class="ClassName" />
Example:
<jsp:useBean id="user" class="[Link]" />
4. jsp:setProperty ac on tag
The jsp:setProperty tag is used to set the value of a property in a bean.
Example:
<jsp:useBean id="user" class="[Link]" />
<jsp:setProperty name="user" property="name" value="Raghav" />
5. jsp:getProperty ac on tag
The jsp:getProperty tag is used to display the value of a bean property.
Example:
<jsp:getProperty name="user" property="name" />
6. jsp:param ac on tag
The jsp:param tag is used to pass parameters along with forward or include.
Example:
<jsp:forward page="[Link]">
<jsp:param name="name" value="Raghav" />
</jsp:forward>
In [Link]:
<%
String name = [Link]("name");
[Link](name);
%>
7. jsp:plugin ac on tag
The jsp:plugin tag is used to embed Java components like applets into the JSP page.
Example:
<jsp:plugin type="applet" code="[Link]" width="300" height="200" />
JSTL (JSP Standard Tag Library)
JSTL (JSP Standard Tag Library) is a collec on of standard predefined tags provided by Java to
simplify JSP development. It is mainly used to reduce the use of Java code (scriptlets) inside
JSP pages and make the code more readable and maintainable.
Instead of wri ng Java code inside <% %>, JSTL allows performing opera ons like looping,
condi on checking, forma ng and database access using simple tags.
JSTL works with Expression Language (EL), which makes it easier to access data without
wri ng Java code.
Types of JSTL Tags:
JSTL provides different types of tags:
Core tags → used for basic opera ons like loops and condi ons
Func on tags → used for string opera ons
Forma ng tags → used for date, number forma ng
XML tags → used for XML processing
SQL tags → used for database opera ons
Advantages of JSTL
JSTL makes development faster because it removes the need to write Java code inside JSP. It
improves readability of code and promotes clean separa on of logic and presenta on. It also
increases reusability since the same tags can be used across mul ple JSP pages.
Example of JSTL
<%@ taglib uri="h p://[Link]/jsp/jstl/core" prefix="c" %>
<html>
<body>
<c:forEach var="i" begin="1" end="3">
<p>Number: ${i}</p>
</c:forEach>
</body>
</html>
In this example, the loop is wri en using <c:forEach> instead of Java code. ${i} is an EL
expression used to display values.
Custom Tags in JSP
Custom tags in JSP are user-defined tags created by the programmer to perform specific
tasks. They reduce the use of scriptlet code in JSP pages and help in separa ng presenta on
from business logic. Instead of wri ng Java code again and again inside JSP, we can define
our own tag and reuse it in mul ple pages.
Custom tags improve code readability, reusability and maintainability. They are especially
useful when the same logic is required in many JSP pages.
Advantages of Custom Tags
Custom tags eliminate the need for scriptlet tags, which are generally considered poor
prac ce in JSP. They separate business logic from the JSP page, making the page easier to
read and maintain. They also support reusability because the same custom tag can be used
many mes in different JSP files.
Syntax of Custom Tag
A custom tag can be used in either of the following forms:
<prefix:tagname a r1="value1" ... a rn="valuen" />
or
<prefix:tagname a r1="value1" ... a rn="valuen">
body content
</prefix:tagname>
Here, prefix is the library prefix declared using the taglib direc ve, and tagname is the name
of the custom tag.
JSP Custom Tag API
The JSP Custom Tag API is provided in the [Link] package. It contains
interfaces and classes required for crea ng custom tags.
The root interface in the custom tag hierarchy is JspTag.
The main hierarchy is as follows:
JspTag → root marker interface
Tag → sub-interface of JspTag
Itera onTag → sub-interface of Tag
BodyTag → sub-interface of Itera onTag
TagSupport → helper class implemen ng Itera onTag
BodyTagSupport → helper class implemen ng BodyTag
SimpleTag and SimpleTagSupport are used in the simpler tag model
In most prac cal examples, TagSupport is commonly used because it provides default
implementa on and makes development easier.
JspTag Interface
JspTag is the root interface for all JSP custom tags. It is a marker interface, which means it
does not define methods directly but serves as the parent for other tag interfaces.
Tag Interface
The Tag interface is a sub-interface of JspTag. It defines methods that are executed at the
start and end of a tag.
Important Constants of Tag Interface
EVAL_BODY_INCLUDE means the body of the tag will be evaluated.
SKIP_BODY means the body of the tag will not be evaluated.
EVAL_PAGE means the rest of the JSP page will con nue to execute a er the tag.
SKIP_PAGE means the remaining JSP page will not be executed a er the tag.
Important Methods of Tag Interface
setPageContext(PageContext pc)
This method sets the PageContext object for the tag.
setParent(Tag t)
This method sets the parent tag object.
getParent()
This method returns the parent tag object.
doStartTag()
This method is called when the start tag is encountered. The programmer overrides this
method to define logic to be executed at the beginning of the tag.
doEndTag()
This method is called when the end tag is encountered. It defines logic to be executed at the
end of the tag.
release()
This method is used to release resources and reset the tag state.
Itera onTag Interface
Itera onTag is a sub-interface of Tag. It is used when the body of a tag has to be evaluated
mul ple mes.
Constant of Itera onTag
EVAL_BODY_AGAIN means the tag body should be evaluated again.
Method of Itera onTag
doA erBody()
This method is invoked a er evalua ng the body content. If it returns EVAL_BODY_AGAIN,
the body is processed again. If it returns SKIP_BODY, the repe on stops.
TagSupport Class
TagSupport is a convenience class that implements the Itera onTag interface. It provides
default implementa on of methods, so the programmer usually extends this class instead of
implemen ng the interfaces directly.
It acts as a base class for crea ng custom tag handlers.
Steps to Create a JSP Custom Tag
To create a custom tag, the following steps are followed:
First, create the Tag Handler class containing the Java logic.
Second, create the TLD file (Tag Library Descriptor) which defines the tag and maps it to the
handler class.
Third, create the JSP file that uses the custom tag through the taglib direc ve.
Example 1: Custom Tag to Print Current Date and Time
1. Tag Handler Class
File: [Link]
package [Link];
import java.u [Link];
import [Link] on;
import [Link];
import [Link];
public class MyTagHandler extends TagSupport {
@Override
public int doStartTag() throws JspExcep on {
JspWriter out = [Link]();
try {
[Link]([Link]().getTime());
} catch (Excep on e) {
[Link](e);
}
return SKIP_BODY;
}
}
Explana on
Here, the class extends TagSupport.
The doStartTag() method is overridden because the ac on has to be performed when the
tag starts.
[Link]() returns a JspWriter object which is used to print output to the JSP
page.
SKIP_BODY is returned because this tag does not process any body content.
2. TLD File
File: [Link]
Place it inside the WEB-INF folder.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"h p://[Link]/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>h p://[Link]/example-taglib</uri>
<tag>
<name>today</name>
<tag-class>[Link]</tag-class>
</tag>
</taglib>
Explana on
The TLD file defines the tag library.
<name> gives the tag name to be used in JSP.
<tag-class> specifies the full class name of the handler class.
3. JSP File
File: [Link]
<%@ taglib uri="WEB-INF/[Link]" prefix="m" %>
<html>
<body>
Current Date and Time is: <m:today />
</body>
</html>
Output
The browser will display the current date and me.
A ributes in JSP Custom Tag
Custom tags can also take a ributes, just like HTML tags.
To define an a ribute in a custom tag, two things must be done:
First, define a property in the Tag Handler class and provide its se er method.
Second, define the a ribute in the TLD file inside the <tag> element.
For example:
<m:cube number="4" />
Here:
m is the prefix
cube is the tag name
number is the a ribute
Example 2: Custom Tag with A ribute
This example computes the cube of a number.
1. JSP File
File: [Link]
<%@ taglib uri="WEB-INF/[Link]" prefix="m" %>
<html>
<body>
Cube of 4 is: <m:cube number="4" />
</body>
</html>
2. Tag Handler Class
File: [Link]
package [Link];
import [Link] on;
import [Link];
import [Link];
public class CubeNumber extends TagSupport {
private int number;
public void setNumber(int number) {
[Link] = number;
}
@Override
public int doStartTag() throws JspExcep on {
JspWriter out = [Link]();
try {
[Link](number * number * number);
} catch (Excep on e) {
[Link]();
}
return SKIP_BODY;
}
}
Explana on
The a ribute number is declared as an instance variable.
The se er method setNumber() is used by the container to pass the value from the JSP tag
into the handler class.
Then doStartTag() calculates and prints the cube.
3. TLD File
File: [Link]
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"h p://[Link]/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>h p://[Link]/example-taglib</uri>
<descrip on>A simple tag library for examples</descrip on>
<tag>
<name>cube</name>
<tag-class>[Link]</tag-class>
<a ribute>
<name>number</name>
<required>true</required>
</a ribute>
</tag>
</taglib>
Output
If the input is 4, the output will be:
Cube of 4 is: 64
Custom URI in JSP Custom Tag
Instead of directly giving the TLD file path in the JSP page, we can define a custom URI in the
[Link] file. Then JSP can refer to the tag library using that URI.
This is a be er and cleaner approach.
Example 3: Using Custom URI
This example shows how to use a custom URI for the tag library.
1. JSP File
File: [Link]
<%@ taglib uri="mytags" prefix="m" %>
<html>
<body>
Today is: <m:today />
</body>
</html>
2. [Link] File
File: [Link]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Applica on 2.3//EN"
"h p://[Link]/dtd/web-app_2_3.dtd">
<web-app>
<jsp-config>
<taglib>
<taglib-uri>mytags</taglib-uri>
<taglib-loca on>/WEB-INF/[Link]</taglib-loca on>
</taglib>
</jsp-config>
</web-app>
Explana on
<taglib-uri> defines the name used in JSP.
<taglib-loca on> gives the actual loca on of the TLD file.
3. TLD File
File: [Link]
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"h p://[Link]/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>mytags</uri>
<descrip on>A simple tag library for the examples</descrip on>
<tag>
<name>today</name>
<tag-class>[Link]</tag-class>
</tag>
</taglib>
4. Tag Handler Class
File: [Link]
package [Link];
import java.u [Link];
import [Link] on;
import [Link];
import [Link];
public class PrintDate extends TagSupport {
@Override
public int doStartTag() throws JspExcep on {
JspWriter out = [Link]();
try {
[Link](new Date());
} catch (Excep on e) {
[Link]();
}
return SKIP_BODY;
}
}