0% found this document useful (0 votes)
35 views117 pages

Servlets & JSP

Session tracking maintains user data across requests by assigning a unique ID to each user. Common session tracking methods include cookies, hidden form fields, and URL rewriting. The HttpSession interface represents a user's session and allows storing session attributes.

Uploaded by

shreya tiwari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views117 pages

Servlets & JSP

Session tracking maintains user data across requests by assigning a unique ID to each user. Common session tracking methods include cookies, hidden form fields, and URL rewriting. The HttpSession interface represents a user's session and allows storing session attributes.

Uploaded by

shreya tiwari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 117

Sessions


Session is basically a time frame and tracking means
maintaining user data for certain period of time
frame.

HTTP protocol and web servers are stateless.

All requests and responses are independent.

Each request to the web server is treated as a new
request.

Session Tracking is a mechanism used by the
web
container to store session information for a particular
user. It is used to recognize a particular user.
Methods of Session Tracking
1) Cookies
2) Hidden Form Field
3) URL Rewriting
4) HttpSession
Cookies
Cookies are small piece of information sent by web
server in response header and gets stored in browser
side.
A web server assigns a unique session ID to each
web client.
The cookies are used maintain the session. The
client
can disable the cookies.
Hidden Form Field
The hidden form field is used to insert the
information in the webpages and this information is
sent to the server.
These fields are not viewable to the user directly.

For example:
<input type = hidden' name = 'session' value =
'12345' >
URL Rewriting
Append some extra data through URL as request
parameters with every request and response. URL
rewriting is a better way to maintain session’s
management and work for the browsers.

For example:
http://abcserver.com/servlet.html;jsessionid=54321
HttpSession Object
The HttpSession object represents a user session. The
HttpSession interface creates a session between an
HTTP client and HTTP server.
A user session contains information about the user
across multiple HTTP requests.

For example:
HttpSession session = request.getSession( );
Session.setAttribute("username", "password");
Cookies

Cookies are small piece of data on the client
computer that send response from the web server to
client.

They are used to store the client state.

The information which is stored on the client
machine is called cookie.

A Servlet container sends small information to the
web browser. This data is saved by the browser and
later back to the server.

The servlet sends cookies to the browser
using HttpServletResponse.addCookie(javax.servl
et.http.Cookie) method.
Types of Cookies
Two types of cookies presents in Servlets:
1. Non-persistent/session cookie
2. Persistent cookie
Non-persistent/session cookie
Non-persistent cookies do not have an expiry time.
They are valid for a single session only.
The persistent cookies are live till the browser is
open.
They disappear when user closes the browser.
Persistent cookie
Persistent cookies have expiry time parameter. They
are valid for multiple sessions.
They do not disappear when user closes the browser.
They are stored in primary memory of the
computer. They disappear when user logs out or
signs out.
Cookie Class Constructors
Constructor Description
Cookie( ) Constructs the cookie with
default property.
Cookie(String name, Constructs a cookie with
String value) specified name and value.
Cookie Class Methods
Methods Description
public String Returns the name of the
getName( ) cookies.
public String Returns the path of the
getPath( ) server to which the
browser returns the cookie.
public String Returns the value of the
getValue( ) cookie.
public int Returns the maximum age
getMaxAge( ) limit to the cookie,
specified in seconds.
public void Sets the maximum age of
setMaxAge(int the cookies in seconds.
expiry)
public void Allocates a new value to a
setValue(String cookie after the cookie is
newValue) created.
Create a Cookie Object
The constructor of Cookie class creates the cookie
object with corresponding cookie name and
value.
Example
Cookie cookie = new Cookie("username","Surendra");
response.addCookie(cookie);
Reading Cookie Sent from the Browser
The getCookies( ) method is used for getting the cookie.
Example
Cookie[ ] cookies = request.getCookies( ); String
username = null;
for (Cookie cookie : cookies)
{
if("user".equals(cookie.getName( )))
{
username = cookie.getValue();
}
}
Deleting the Cookies
We can remove the cookies from the browser by
setting the cookie expiry time to 0 or -1.
Example
Cookie cookie = new Cookie("user", "");
cookie.setMaxAge(0);
response.addCookie(cookie);
Database Access in Servlets

To access the database in Servlet, load the JDBC
driver and return the Connection object.

The Connection object is used to create
Statement
object.

Before starting with database access through servlet,
make sure that the proper JDBC connection with
database has been setup.
Accessing a Database
Following files are required for accessing the
database:
i. welcome.html
ii. ServletDatabaseDemo.java
iii. web.xml
iv. ojdbc14.jar

Note: We are using Oracle database and type 4


(thin driver) to connect with Servlet application.
Example : Accessing the database and displaying
the record
//welcome.html
<form action="showrecords" method="post">
Enter Table Name : <input type="text"
name="table">
<input type="submit" value="Show
Records">
</form>
//ServletDatabaseDemo.java
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import
javax.servlet.http.*;

public class ServletDatabaseDemo extends


HttpServlet
{
protected void doPost(HttpServletRequest req,
HttpServletResponse res)throws
ServletException,IOException{
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
String tableName = req.getParameter("table");
try {
Class.forName("oracle.jdbc.driver.Oracle
Dr
iver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@lo
calhost:1521:XE","scott","tiger");
Statement
st=con.createStatement();
System.out.println ("connection established
successfully...!!");
ResultSet rs =
st.executeQuery("Select *
pw.println("<table border=1>");
while(rs.next())
{
pw.println("<tr><td>"+rs.getInt(1)+"</td>
<td>"+rs.getString(2)+"</td>
<td>"+rs.getString(3)+"</td>
<td>"+rs.getString(4)+"</td>
</tr>");
}
pw.println("</table>");
pw.close();
rs.close();
con.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
//web.xml
<web-app>
<servlet>
<servlet-name>ServletDBConnection</servlet-
name>
<servlet-class>ServletDatabaseDemo</
servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>ServletDBConnection</servlet-
name>
<url-pattern>/showrecord</url-pattern>
</servlet-mapping>
</web-app>
RequestDispatcher and
Page Redirection in Servlets

The RequestDispatcher is an interface that defines
an object to receive request from the client and sends
them to any resource on the server.

It implements an object to wrap together different
types of resources in Servlet container.
RequestDispatcher Methods
The RequestDispatcher interface provides two
methods:
Methods Description
public void It forwards a client request
forward(ServletRequest from a servlet to another
request, resource (servlet, JSP file,
ServletResponse HTML file) on the
response) server.

public void Includes the content of a


include(ServletRequest resource (Servlet, JSP
request, pages, HTML file) in the
ServletResponse response.
response)
Getting the Object of
RequestDispatcher
ServletRequest interface provides the
getRequestDispatcher( ) method to returns the
object of RequestDispatcher.
Example
RequestDispatcher rd =
request.getRequestDispatcher("index.html");
rd.forward(request, response);

OR

RequestDispatcher rd =
request.getRequestDispatcher("index.html");
rd.include(request, response);
Page Redirection

The Page redirection is the process of redirecting the
response to another resource.

It is used to move the document to the new location
for load balancing or simple randomization.

The sendRedirect( ) method is the method of
HttpServletResponse interface.

It is used to redirect response to another resource
(servlet, jsp or HTML file).
For example:
response.sendRedirect("index.html");
Difference between forward( ) method and
sendRedirect( ) method
forward( ) sendRedirect( )
Used to forward the Used to redirect the
resources available resources to different servers
within the server. or domains.
The forward( ) method The sentRedirect( ) method
is executed on the is executed on the client
server side. side.
The forward( ) method It is slower because each
is faster than time a new request is
sendRedirect( ). created, old one is lost.
The transfer of control The transfer of control is
is done by container assigned to the browser and
and client/browser is a new request to the given
not involved. URL is initiated.

The request is shared New request is created for


by the target resource. the server resource.
It is declared in It is declared in
RequestDispatcher HttpServletResponse.
interface.
Example : Illustrating the sendRedirect( ) method
for page redirecting in Servlet
//SendRedirectDemo.java
import java.io.*;
import javax.servlet.*;
import
javax.servlet.http.*;
public class
SendRedirectDemo
extends HttpServlet
{
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter pw = response.getWriter();
response.sendRedirect("http://an
yserver.com/") pw.close();
}
}
Java Server Pages

Java Server Pages (JSP) is a server-side scripting
technology.

It helps to create dynamic and platform-independent
web-based applications.

JSP is an extension of Servlet API and given by Sun
Microsystems.

JSP contains HTML tags and can add Java codes
inside the HTML.

JSP separates presentation and business logic as the
web designer can update JSP pages without
knowledge of Java programming.

JSP tags start with "<%" and end with "%>".

JSP is used to collect input from users through web
page forms, present records from a database, pass
control between pages and share information.
Advantages of JSP

JSP is easy to maintain. It can easily separate
business logic from presentation logic.

JSP is developed in Java language so it is portable to
other operating systems.

JSP is the extension of Servlet. It has high
performance and scalability.

It reduces the size of code because it uses lots of
action tags, custom tags etc.

JSP provides the fast development because if the
page is modified there is no need to recompile and
redeploy the application.
Architecture of JSP
Life Cycle of JSP Page

Translation of JSP page.

Compilation of JSP page.

Loading the class.

Instantiation of Servlet objects.

Initialization by calling jspInit( ) method.

Request Processing by calling _jspService( ) method.

Destruction by calling jspDestroy( ) method.

First when a web browser asks for JSP , the Web
container translates JSP code into a servlet(.java)
file, and then the compiler compiles it into .class file.

In the next step the classloader loads the servlet class
bytecode.

Web container calls the jspInit() method to load JSP
class. For each request the web container invokes
the _jspService( ) method.

Finally the jspDestroy( ) method is invoked for
cleanup.
Example
jspInit( ) method
public void jspInit( )
{
//code
}
_jspService( ) method
void _jspService(HttpServletRequest request,
HttpServletResponse response)
{
//service code
}
jspDestroy( ) method

public void jspDestroy( )


{
//cleanup code
}
Scripting Elements
The scriptlet tag is used to write the Java code inside
the JSP page. JSP scripting elements are written
inside <% %> tags.
Three types of scripting elements:

scriptlet tag

declaration tag

expression tag
JSP scriptlet tag
JSP scriptlet tag is used to write Java code inside JSP
page. It executes source code.

Syntax:
<% java code %>
Example : implements JSP scriptlet tag
<html>
<head>
<title>
My First JSP Page
</title>
</head>
<body>
<% out.print("Welcome to JSP world"); %>
</body>
</html>
Output:
Welcome to JSP world
JSP Declaration Tag

JSP declaration tags are used to declare variable
fields and methods.

The declaration tag is placed outside the service
method and inside the Servlet class to make them
class level variable and methods.
Syntax:
<%! Declaration %>
Example : Declaring a method inside Declaration
Tag
<html>
<head>
<title>JSP Declaration Tag</title>
</head>
<body>
<%! int square(int a){
return a * a;
}
%>
<% = "Square of 5 is:
"+square(5) %>
</body>
</html>

Output:
Square of 5 is: 25
JSP Expression Tag

JSP expression tag is used to write the client
response to the output stream.

Expression tag keeps the expression that can be used
as an argument to the output stream method.
Syntax:
<%= Java Expression %>
Example : Displays current date using Expression
tag
<%@page contentType="text/html"
import="java.util.*" %>
<html>
<head>
<title>JSP Expression
Tag</title>
</head>
<body>
<h2>Current Date</h2>
<p>
Today's Date: <%= (new
java.util.Date()).toLocalString() %>
</p>
</body>
</html>

Output
:
Today’s
Date:
03-
Aug-
2016
10:52:2
1
JSP Comments

JSP comment is text or statement that is not
considered by JSP container.

JSP comments are hidden in JSP page source and
ignored by JSP container.
Syntax:
<%-- JSP comment --%>
Example : JSP comment tag
<html>
<head>
<title>JSP Comments</title>
</head>
<body>
<%-- this will hide on JSP page --%>
</body>
</html>
JSP Implicit Object
JSP implicit objects are created by the web container
and available to all JSP pages. They are basically
Java object which also called pre-defined variables.
Object Availability and Uses
request The javax.servlet.http.HttpServletRequ
est object is associated with the request.
response The javax.servlet.http.HttpServletResp
onse object is associated with the
response.
out The javax.servlet.jsp.JspWriter object is
used to send output the client.
session The javax.servlet.http.HttpSession objec
t is associated with the session for the
given client request.
Applicati The javax.servlet.ServletContext object
on is used for the web application.
config The javax.servlet.ServletConfig object is
associated with the Servlet for current
JSP page.
pageCont The javax.servlet.jsp.PageContext objec
ext t encapsulates the environment of a
single request for the current JSP page.
page The page variable is similar to this
reference of Java. It is available
in java.lang.Object class.
exception The Exception object represents
the Throwable object that was thrown by
some other JSP page.
Example : Implementing Request Object
//welcome.html
<html>
<head>
<title>Username & Password</title>
</head>
<body>
<form action="welcome.jsp">
Enter User Name: <input type="text"
name="uname" /> <br>
Enter Password: <input type="text"
name="pass" /> <br>
<input type="submit"
value="Submit"/>
<input type = "submit"
value = "Reset">
</form>
</body>
</html>

//welcome.jsp
<%@ page import = " java.util.* "
%>
<html>
<%
String username =
request.getParameter("uname");
String password =
request.getParameter("pass");
out.print("Welcome: "+username);
%>
</body>
</html>
Example : Implementing session Object
//index.html
<html>
<body>
<form action="session.jsp">
<input type="text" name="uname">
<input type="submit" value="Click
here!"><br/>
</form>
</body>
</html>
//session.jsp
<html>
<head>
<title>Passing Session Variables</title>
</head>
<body>
<%
String name = request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
<a href="display.jsp">Display Page</a>
%>
</body>
</html>

//display.jsp
<html>
<body>
<%
String
name=(String)session.getAttribute("user");
out.print("Welcome "+name);
%>
</body>
</html>
Example : Implementing config Object
//welcome.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="Click
here!!"><br/>
</form>
//web.xml
<web-app>
<servlet>
<servlet-name>Welcome</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
</servlet>

<servlet-mapping>
<servlet-name>Welcome</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
//welcome.jsp
<html>
<head>
<title>Config Implicit Object</title>
</head>
<body>
<%
String sname = config.getServletName();
out.print("Servlet Name: "+sname);
%>
</body>
</html>
Form Processing in JSP
Forms are the basic components that help us interact
with web pages.
The form processing became very easy with the help
of JSP. The browser uses the GET
method and POST method for passing the
information to the webserver.
GET Method
The GET method is used to send the encoded user
information appended to the page URL. Each
encoded information is separated by '?' character.
GET is a default method to send information to web
server. We should avoid using GET method to
send sensitive information like as password etc.
For example:
http://www.abcserver.com/hello?key1=value&key2=
value2
GET Method Example
<html>
<head>
<title>Reading data by Using GET
method</title>
</head>
<body>
<h1>GET method</h1>
<ul>
<li><p><b>Name:</b>
<%=
request.getParameter("name")
%>
</p></li>
<li><p><b>City:</b>
<%= request.getParameter("city")%>
</p></li>
<li><p><b>Profession:</b>
<%= request.getParameter("prof")%>
</p></li>
</ul>
</body>
</html>
POST Method
The POST method is used to send large amount of
data on web server. When we want to send any
sensitive data on web page, the POST method should
be used as instead of sending text string in URL, it
sends the encrypted message.
Example: Implementing POST method using Form
//welcome.html
<html>
<head>
<title>Using POST method</title>
</head>
<body>
<h2>Using POST method</h2>
<form action = "welcome.jsp" method = "POST">
Name: <input type = "text" name = "name"/>
City: <input type = "text" name = "city"/>
Job: <input type = "text" name = "job">
<input type = "submit" value = "Submit">
</form>
</body>
</html>

//welcome.jsp
<html>
<head>
<title>JSP page using POST method</title>
</head>
<body>
Name: <%= request.getParameter ("name") %>
City: <%= request.getParameter ("city") %>
Job: <%= request.getParameter ("job") %>
</body>
</html>
Directive Elements
Directives control the processing of the JSP page.
The directive tag instructs the web container at the
time of translating a JSP page into the corresponding
Servlet page.

There are 3 types of directives in JSP:


i. page directive
ii. include directive
iii. taglib directive
Syntax of Directive:
<%@ directive attribute= "value" %>
page directive
The page directive allows applying different
attributes to be added in JSP.
These attributes give special processing information
to the JSP container.
Following are the page directive attribute:

Attribute Description
import Import list of packages, classes and
interfaces in servlet class
definition.
Example: <%@ page import =
"java.util.Date" %>
extends Used to extend the parent class that
will be generated by Servlet.
Example: <%@ page extends =
"mypackage.DemoClass"%>
language Defines which scripting language
to be used in the page.
Example: <%@ page language
=
"value"%>
session Specifies the JSP page
participating in an HTTP session.
Example: <%@ page session =
"true"%>
buffer Specifies a buffer model to handle
output stream generated by JSP
page.
Example: <%@ page buffer =
"4kb"%>
autoFlush Specifies that buffer should be
flushed automatically. The default
value of autoFlush attribute
is ‘true’.
Example: <%@ page autoFlush =
"false"%>
info Sets the information of the JSP
page which is retrieved later by
using getServletInfo( ) method.
Example: <%@ page info =
"Given by Surendra Maurya"%>
contentType Sets the content of the JSP page.
Example: <%@ page
contentType="text/html"%>
isThreadSafe It is used to define the threading
model for the JSP page which is
generated by Servlet because JSP
and servlet both are thread safe.
Example: <%@ page
isThreadSafe="false"%>
errorPage Define the error page, if any error
generates in current page, it will be
redirected to the error page.
Example: <%@ page
errorPage="erroropage.jsp"%>
isErrorPage Defines whether the current JSP
page is error page or not.
Example: <%@ page
isErrorPage="true" %>
isELIgnored Specifies whether the expression
will be evaluated or not in JSP
page.
Example: <%@ page
isELIngored="true" %>
include directive

The include directive is used to insert a file like a
JSP file, HTML file or text file. It will parse the JSP
elements during the translation phase.

The main advantage of the include directive is
code reusability functionality.
Syntax:
<%@ include file="resourceName" %>
Example
<html>
<head>
<title>Include Directive</title>
</head>
<body>
<%@ include file = "header.jsp">
</body>
</html>
taglib directive

It is used to define a tag library that contains many
custom tags.

JSP technology supports the development of reusable
components called custom actions.

The custom tags can be customized by passing the
attribute from invoking page.

It can be accessed by all the available objects on the
JSP page.
Syntax:
<%@ taglib prefix="prefixOfTag"
uri="uriOfTagLibrary" %>
Example
<html>
<head>
<title>Taglib directive</title>
</head>
<%@ taglib prefix="myTag" uri
="http://www.abcserver.com/java-
technologies.htm" %>
<body>
Welcome, <myTag:userName
/>
</body>
</html>
Exception Handling

Exception is an event that arises during the execution
of the program.

It terminates the program abnormally.

Exception handling is the process of handling the
abnormal termination of the program.

Exception handling in JSP is easier than in Java
technology.

JSP also uses the same exception class object.

There are two ways to perform Exception


Handling in JSP:
1.Using isErrorPage and errorPage attribute of
page directive.
2. Using <error-page> tag in Deployment
Descriptor.

Example : Exception handling using isErrorPage &


errorPage attribute
//result.jsp
<%@ page errorPage="error.jsp" %>
<html>
<head>
<title>JSP Exception Handling</title>
</head>
<body>
<%
int a = 46;
int b = 0;
int result
= a/b ;
%>
</body>
</html>
//error.jsp
<%@ page isErrorPage = "true" %>
<html>
<head>
<title>Exception Page</title>
</head>
<body>
<h3>Sorry an exception occured!</h3>
Exception is: <%= exception %>
</body>
</html>
Using try and catch Block
In JSP, we can also handle the exception by using try
and catch block. It works on same page instead of
firing an error page.

Example : Using try & catch block in JSP page for


exception handling
<html>
<head>
<title>Exception handling in JSP using try
catch blocks</title>
</head>
<body>
<%
try
{
i
n
t
a
r
r
[
]
=
}
%>
</
body
>
</
html
>
Action Element in JSP
JSP actions can be used to print a script expression,
create and store a Java Bean and for many other
things. They are used for constructs in XML syntax
to control the behavior of the Servlet engine.

Using JSP actions



a file can be inserted into another page
dynamically,

a bean component can be reused,

a user can be forwarded from one page to another
page.
Following are the JSP action tags:

Action tags Description


<jsp:include> Includes a file at the time
when the page is requested.
<jsp:useBean> Finds the object of Java bean
from a given scope or
creates a new object.
<jsp:setProperty> Sets the property of a
JavaBean object.
<jsp:getProperty> Prints the property of the Java
bean object.
<jsp:forward> Forwards the request and
response to another resource.
<jsp:plugin> It is used when there is a need
of a plugin to run a Bean
class.
<jsp:param> Sets the parameter value to the
request. It is used in forward
and include mostly.
<jsp:fallback> Supplies alternate text if Java
applet is unavailable on the
client.
<jsp:element> Defines XML element
directly.
The <jsp:include> Action Tag
Syntax:
<jsp:include page="page URL" flush="Boolean
Value" />
Example : Illustrating the <jsp:include> tag
//welcome.jsp
<p>
Today's date: <%= new java.util.Date()%>
</p>
//demo.jsp
<html>
<head>
<title>JSP include Action Tag</title>
</head>
<body>
<h3>JSP page: Demo Include</h3>
<jsp:include page = "welcome.jsp" />
</body>
</html>
The <jsp:forward> Action Tag
Syntax:
<jsp:forward page="Relative URL" />

Example : Illustrating the <jsp:forward> action tag


<html>
<head>
<title>JSP Forward Action Tag</title>
</head>
<body>
<h2>JSP page: Demo forward</h2>
<jsp:forward page="welcome.jsp" />
</body>
</html>
The <jsp:setProperty> Action Tag
It is used to set the property of a Bean.

Syntax:
<jsp: useBean id="instanceOfBean"
class="package_name.class_name" />
....
....
<jsp:setProperty name="instanceOfBean"
property="property_name" />
The <jsp:getProperty> Action Tag
It is used to return the value of the property.

Syntax:
<jsp:getProperty name="instanceOfBean"
property="propertyName" />
Custom Tags in JSP

Custom tags are user-defined tags.

Custom tags are distributed in a tag library which
defines a set of related custom tags.

They are used to remove the complexity of the
business logic and separate it from the JSP page.

It also provides the code reusability of the custom
tag.
Syntax
1. Create an empty tag:
<prefix:tagname attr1=value1....attrn=valuen />

2. Create a Custom tag:


<prefix:tagname attr1=value1....attrn=valuen>
body code
</prefix:tagname>
Creating a Custom Tag
To create a custom tag, we need three things.
i. Tag handler class
ii. Tag Library Descriptor (TDL) file
iii. Use the Custom tag in the JSP file.
Tag Handler Class
We can create a custom tag by implementing
SimpleTag, Tag or BodyTag interface during the
life cycle of the tag.
There is a getOut( ) method in pageContext class
that returns the instance of JspWriter class.
All the classes that support custom tag are present
inside javax.servlet.jsp.tagext.

Example : Creating own custom tag


//TagHandlerDemo.java

package com.anyserver.com;
import java.util.Calendar;
import java.io.*;
import
javax.servlet.jsp.JspExceptio
n;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class TagHandlerDemo extends TagSupport
{
public intdoInstantTag() throws JspException
{
JspWriter out=pageContext.getOut();
try
{
out.print("This is custom Tag");
out.print(Calendar.getInstance().getTime());
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Tag Library Descriptor
It is an XML document contained inside the WEB-
INF directory.
It has the information of tag and Tag Handler class.
TDLs are used by the JSP web container to
validate the tags.

The extension of Tag Library Descriptor must


be .tdl
Example : Creating own custom tag by using Tag
Library handler
//taglb.tdl

<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Custom Tag Demo</short-name>
<uri>http://to
mcat.apache.org/example- taglib</uri>
<tag>
<name>WelcomeMsg</name>
<tag-
class>anyserver.com.Details</tag-
class>
<body-content>empty</body-content>
</tag>
</taglib>
Use the Custom tag in the JSP File
The taglib directive in JSP page must specify the path
of the URI (Uniform Resource Identifier) field in
TDL path.

It provides the taglib directive that is used to define


in the tdl file.
Example :Creating own custom tag in JSP file
//welcome.jsp
<%@ taglib prefix="mypre" uri="WEB-
INF/msg.tld"%>
<html>
<head>
<title>Custom Tags in JSP
File</title>
</head>
<body>
<myprefix:MyMsg/>
Current Date and Time: <m:today/>
</body>
</html>

You might also like