Sei sulla pagina 1di 196


Understanding JSP
•Java Server Pages is another server-side
technology defined by Sun Microsystems
to generate dynamic web content.
•They are direct extension of servlets.
•They are more efficient than servlets.
•JSP is a type of server-side scripting
•JSP program files have an extension .jsp
Understanding JSP
•They are HTML documents which are
embedded with Java code using different
JSP tags.
•When compared with servlets they are
unstructured and contains pieces of java
code scattered through out an HTML file.
•Since they are server-side applications,
they have access to server resources such
as servlets, javabeans, Ejbs and databases.
Advantages of JSP
•JSP’s being Java programs, they allow
write-once, run-anywhere policy.
•JSP tags are simple to understand, since
they are similar to HTML and XML.
•Since there is a standard, published API
for JSP, and because of Java code
portability, use of JSP is independent of
hardware, OS or server software. 4
Advantages of JSP
• JSP being vendor-neutral, developers and
system architects can select best-of-breed
solutions at all stages of JSP deployment.
• It has full access to the underlying J2SE
APIs (database access, directory services,
distributed computing, cryptography…).
• Hence JSP is highly flexible and feature-
rich to create web-based applications.
Advantages of JSP
• Does not require server restart when
the JSP program code changes.
• Separation of roles into graphical
content and dynamic content.
• JSP’s being a modified way of writing
servlets, they can provide all
features/capabilities of a servlets.
JSP History
• Servlets first appeared as part of Sun’s
Java Web Server (JWS), a Java based
HTTP server in 1997.
• Sun eventually released the Servlet
technology as a standard Java
• JSP soon followed, with the first draft
API specifications appearing in 1998.
JSP History

• JSP 1.0 Specification was

released in June 1999 as a
part of J2EE.
• JSP 1.1 - Late 1999.
• JSP 1.2 - 2001.
• JSP 2.0 – 2003.
Third party vendor support
•RAD tools are now available to create
dynamic web pages, using DnD approach.
•Ability to create sophisticated JSP pages
without seeing HTML tags, let alone Java
code will enhance the productivity to a
greater extent.
•Ex: Drumbeat 2000 from Macromedia
IBM’s Visual Age for Java
HomeSite from Allaire
Features Asp Jsp
WEB Server IIS, PWS Many
Platform Windows Any
Reusable components Com Javabeans/EJB
Memory leak No Yes
Scripting languages J-script, Java
Security No yes
Customized tags No yes
• JavaScript
– Validates on Client Side
– Browser Dependent
– Unstable
– Interpreted

– Server-side JavaScript is dependent

on proprietary servers. 11
JSP vs Servlets
• Similarities
– Provides identical results to end
– JSP is an extension of servlets.
– Provides similar API support.

JSP vs Servlets
• Differences
– Servlets: “HTML embedded in Java Code”
HTML code inaccessible to Graphics designer
But accessible to Programmer.
– JSP: “Java Code embedded in HTML”
HTML code accessible to Graphic Designer
Java code accessible to Programmer.
– Jsp allows code update without restarting
the server.
– Eliminates redundant code. 13
Comparing servlet and JSP code
1. import*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;

5. public class HelloWorld extends HttpServlet

6. {
7. public void doGet(HttpServletRequest req, HttpServletResponse res)
8. throws ServletException, IOException
9. {
10. res.setContentType("text/html");
11. PrintWriter out = res.getWriter();
12. out.println("<HTML>");
13. out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
14. out.println("<BODY>");
15. out.println("<BIG>Hello World</BIG>");
16. out.println("</BODY></HTML>");
17. }
18. }
Comparing servlet and JSP code

1. <HTML>
2. <HEAD> <TITLE>Hello World</TITLE></HEAD>
3. <BODY>
4. <h2>Hello World </h1>
5. </BODY>
6. </HTML>

Note: HTML content is also valid JSP content, since JSP is HTML
code embedded with java code.
JSP functionality
Web Server
JSP Page

qu est Translation by
Re JSP engine

Web Generated Servlet


sp Compiled Servlet

Servlet is loaded to

JSP life cycle
• jspInit()
• jspDestroy()
• _jspService( request, response )

_jspService(request,response) jspDestroy()
Handle Requests: Invoked by
Initialise JSP
invoked container
Invoked only once
for every request to cleanup

•Implementation of these methods are generated

by the Container and not by JSP authors.

JSP and the JSP Engine
• Contract between the JSP engine and JSP
– jspInit() Corresponds to servlet init(), but
has no parameters (use config implicit
object to obtain information regarding
– jspService() The main processing method;
all Java code belongs to this method by
default (if not contained in another
method), but it is not explicitly declared in
a JSP document.
– jspDestroy() Corresponds to the servlet 18
Package java.servlet.jsp
Interface Hierarchy

Class Hierarchy

•Top most in the servlet API hierarchy.
•It is implemented by
javax.servlet.GenericServlet, which is further
extended by javax.servlet.http.HttpServlet.
•public void init(ServletConfig config)
•public void service( ServletRequest req,
ServletResponse res)
•public void destroy()

•public ServletConfig getServletConfig()

•public String getServletInfo()
Interface JspPage
• It describes the generic interaction that a JSP
Page implementation class must satisfy.
• Pages that use HTTP protocol are described by
HttpJspPage interface.

– public void jspInit()

Invoked when the JSP page is initialized.
– public void jspDestroy()
Invoked before destroying the JSP page.

• Note: The jspInit() and jspDestroy() can be

defined by a JSP author, but _jspService() is
defined automatically by the JSP processor
based on contents of the JSP page.
• Extends JspPage and describes interaction
that a JSP Page implementation class must
satisfy when using HTTP protocol.
• Behaviour is identical to JspPage, except that
_jspService method is now expressible in Java
type system optimized for HTTP.

– void _jspService( HttpServletRequest

request, HttpServletResponse response)
• It corresponds to body of the JSP page.
• It is defined automatically by the JSP container.
Class JspFactory
•Defines factory methods available to a JSP
page at runtime to enable instantiation of
implementation-dependent PageContext and
JspEngineInfo that support JSP
•JSP Engine, during it's startup instantiates an
implementation dependent subclass of this
•This instance is made globally available by
registering it using setDefaultFactory() method.
Note: JspFactory objects should not be used by
JSP page authors. 23
Class JspFactory
• static void setDefaultFactory(JspFactory deflt)
• static JspFactory getDefaultFactory()
• abstractJspEngineInfo getEngineInfo()
• abstractPageContext getPageContext(
Servlet servlet,
ServletRequest request,
ServletResponse response,
String errorPageURL,
boolean needsSession,
int buffer,
boolean autoflush)
– Instantiates an implementation dependent
PageContext for the calling Servlet.
• abstract void releasePageContext(PageContext pc) 24
Class JspEngineInfo

• Provides information about the

current JSP engine (container).

• abstract String
Return version of the JSP
specification supported by this JSP
May return null, if version details
is not known. 25
Class PageContext
• Provides access to JSP implicit objects
and page attributes.
• It is an abstract class, and is
implemented by container provider.
• It is instantiated using static method
getPageContext() and is released using
releasePageContext() of JspFactory.
Field Summary
• static String APPLICATION
Name used to store ServletContext in PageContext
name table.
• static String CONFIG
Name used to store ServletConfig.
• static String EXCEPTION
Name used for uncaught exception.
• static String OUT
Name used to store current JspWriter.
• static String PAGE
Name used to store the Servlet.
• static String PAGECONTEXT
Name used to store this PageContext. 27
Field Summary…
• static String REQUEST
Name used to store ServletRequest.
• static String RESPONSE
Name used to store ServletResponse.
• static String SESSION
Name used to store HttpSession.

• static int PAGE_SCOPE

• static int REQUEST_SCOPE Indicates
• static int SESSION_SCOPE scope of a bean
• static int APPLICATION_SCOPE reference.
Method Summary
• The following methods provide convenient
access to implicit objects:
• abstract JspWriter getOut()
Returns current value of the out object
• abstract Object getPage()
• abstract ServletRequest getRequest()
• abstract ServletResponse getResponse()
• abstract ServletConfig getServletConfig()
• abstract ServletContext getServletContext()
• abstract HttpSession getSession()
• abstract Exception getException() 29
Method Summary
• Object findAttribute( String name)
Search and return attribute value (or null) in scope
sequence of page, request, session and application.
• Object getAttribute( String name)
Return attribute value of name in page scope.
• Enumeration getAttributeNamesInScope(int scope)
• abstract int getAttributesScope( String name)
• void removeAttribute( String name)
Search for attribute in scope order and remove it.
• void removeAttribute( String name, int scope)
• void setAttribute( String name, Object value)
Register attribute in page scope.
• void setAttribute( String name, Object v, int scope)
Method Summary
• abstract void forward( String relativeUrlPath)
Re-directs/forwards current Request and
Response to another component.
• abstract void include( String relativeUrlPath)
Inserts content/output of refered component.
• abstract void handlePageException
( Exception e)
Redirects exception to the specified error page
(if available) or to default handler.
• abstract void handlePageException
( Throwable t ) 31
Method Summary
• abstract void initialize(Servlet ser,
ServletRequest req, ServletResponse res,
String errorPageURL, boolean needsSession,
int bufferSize, boolean autoFlush)
Initializes PageContext to be used by a JSP to
service an incoming request.

• abstract void release()

It resets PageContext state, releasing internal
references and preparing PageContext for
reuse by a later invocation of initialize(). 32
Method Summary
Following methods enable management of
JspWriter streams to implement Tag Extensions:
• JspWriter popBody()
Returns JspWriter saved by the matching
pushBody(), and updates value of "out“ attribute
in page scope of the PageConxtext.

• BodyContent pushBody()
Returns a new BodyContent object, and updates
the value of "out“ attribute in the page scope
attribute namespace of the PageContext. 33
Class JspWriter
• Provides output stream for JSP's.
• It extends
• A JSPWriter object is available within JSP
as implicit object out, which is initialized
automatically using methods of
PageContext object.
• abstract void clearBuffer()
• abstract void close()
• abstract void flush()
• int getBufferSize()
• abstract int getRemaining()
• boolean isAutoFlush()
• abstract void newLine() 34
Class JspWriter…
void println()
void print(boolean b) void println(boolean x)
void print(char c) void println(char x)
void println(char[] x)
void print(char[] s)
void println(double x)
void print(double d) void println(float x)
void print(float f) void println(int x)
void print(int i) void println(long x)
void print(long l) void println(Object x)
void println(String x)
void print(Object obj)
void print(String s)

Tag convention
• JSP tags usage is similar to those of
HTML tags:
– They begin and end with angle

• JSP tags fall into 2 basic categories:

– Scripting-oriented tags inspired by
– Tags based on XML style.
ASP-like Tags
• They can be recognized by their delimiters.
• They start with <% and end with %>.
• Additional character may appear after the
initial <%, such as !, =, or @, to further specify
the meaning of the tag.
• Example:
<%! double radius = 7.5; %>
<%= 2 * Math.PI * radius %>
<% if (radius > 10.0)
out.println("Exceeds recommended maximum");
} %>
<%@ include file="copyright.html" %> 37
ASP-like Tags…
• NOTE :
– All ASP-scripting like tags are
– All the information relevant to
the tag, and all of the data it
will act on, is contained within
the individual tags themselves.
– None of these scripting-
oriented JSP tags have bodies. 38
XML-like tags
• They start with < and not <%
• Tag names have an embedded colon.
• They are similar to HTML tags; They can have a
"start tag", a "tag body" and an "end tag".
• XML syntax is similar to HTML, but adds a few
rules to avoid certain problems.
– XML tags are case sensitive (<title> and <TITLE>
are treated as two different tags).
– All attribute values must be quoted (In HTML,
quotes are optional).
– All XML tags must also have a delimiting tag.
1. <jsp:forward page="admin.jsp"/>

2. <jsp:useBean id="login“
<jsp:setProperty name="login“

Components of a JSP program

• HTML code
• Comments
• JSP tags
• JSP Implicit Objects
• Java Beans
Comments in JSP
1. Plain HTML Comments
Ex: <!-- hello -->
Response: <!-- hello -->
2. HTML Comments containing JSP tags
Ex: < !-- value of 10 + 20 is <%= 10 + 20 %> -->
Response: <!-- value of 10 + 20 is 30 -->

3. JSP Comment tag

Ex: <%-- This is a JSP comment --%>

4. Java Comments
Ex: <% /* int x;
float f; */
void meth1()
//out.println( “hello output” );
%> 42
JSP tag types
•Declaration tags
•For variable and method declaration
•Format: <%! Variable declaration;
Method declaration;
•Expression tags
•For inserting Java expressions
•format: <%= expression %>
•To embed java code blocks
•format: <% code block %>
JSP tag types…
• To specify information that affect
the whole JSP program
• format: <%@ directive_type
•Action tags
•Used to work with standard objects
<jsp:action_name action_attributes /> or
<jsp:action_name action_attributes> …
</jsp:action_name> 44
General rules
• JSP tags are case sensitive

• Tags may have attributes

• Attribute values must always appear


• White space with in the JSP page is not


• The \ character can be used as an

escape sequence 45
Sample Program -1
•Using simple expression tag

My first JSP program
The Current system date is : <h1> <%= new java.util.Date() %>
Deploying JSP’s on TOMCAT

Deploying JSP’s on J2EE RI

Deploying JSP’s on Weblogic

Deploying JSP’s on JRun

Sample Program - 2
•Hello word example

String name = null;
name = request.getParameter(“name”);
if ( name == null ) {
Hello, World
<% } else
out.println(“Hello ” + name);
%> 51
Sample Program - 3
<html> <body>
Java Version : <%= System.getProperty( "java.version" )
%> <br>
Java Home : <%= System.getProperty( "java.home" ) %>
Os Name : <%= System.getProperty( "" ) %>
User Name : <%= System.getProperty( "" ) %>
User Home : <%= System.getProperty( "user.home" ) %>
User Directory : <%= System.getProperty( "user.dir" ) %>
</body> </html>

Sample Program - 4
•Simple usage of page directive, scriplet and
expression tags.

<%@ page import="java.util.*" %>

System.out.println( "Evaluating date now" );
Date date = new Date();
Hello! The time is now <%= date %>
Sample Program - 5
•Using page directive, declaration tag and expression
tags together.

<%@ page import="java.util.*" %>

Date dateobj = new Date();
Date getDate()
System.out.println( "In getDate() method" );
return dateobj;
Hello! The time is now <%= getDate() %>
</BODY> </HTML> 54
Note about declaration tags
• Declarations in Declaration tag will become
instance members.
• Variables in Declaration tags will be evaluated
only once, during translation of the JSP page.
• Its behavior is same as definition of instance
variables in a class.
• Hence it will not have different functionality
for different clients.
• Client specific data must not be put in
declaration tags, since they are shared.
Sessions can be used for the purpose. 55
Control statements in JSP
Sample Program - 6
•Using if condition statements

<html> <body>
<%! boolean validate_data( String value )
if( value.trim().equals( "xyz" ) ) return true;
else return false;
<% if( validate_data( "hello" ) ) { %>
<h1> Welcome, the data is valid </h1>
<% }else{
out.println( "<h1> invalid data, try again </h1>" );
</body> </html>
Control statements in JSP
Sample Program - 7
•Using for loops

<html> <body>
<%! String items[] = { "bread", "rice", "dal" };
int quantity[] = { 2, 5, 3 };
double cost[] = { 12.50, 19.50, 28.75 };
<table align="center" bgcolor="yellow" border ="1" width="75%" >
<tr> <td> ITEM </td> <td> QUANTITY </td> <td> PRICE </td> </tr>
<% for( int i =0; i < items.length; i++ ) { %>
<td> <%= items[ i ] %> </td>
<td> <%= quantity[ i ] %> </td>
<td> <%= quantity[ i ] * cost[ i ] %> </td>
<% } %>
</body> </html>
Control statements in JSP
Sample Program - 8
•Another example of using for loops
<html> <body>
<% String color_arr[] = { "00", "11", "22", "33", "44", "55", "66", "77", "88",
"99", "AA", "BB", "CC", "DD", "EE", "FF" };
for(int i = 0; i < 5; i++ )
String col = color_arr[ i * 3 ] + color_arr[ i * 3 ] + color_arr[ i
* 3];

<h<%= i %> >

<font color=<%=col%> > Welcome to Step India </font>
</h<%= i %> >

<% } %>
</body> </html> 58
Built-in/Implicit JSP Objects
•Besides objects explicitly created by a
developer within JSP scripting elements, the
JSP container provides a few internal objects,
referred to as implicit objects.
•The developer may assume that these objects
will be automatically assigned to specific
variable names.
•They work as a shorthand for certain
class/interface instances of Servlet/JSP API.
•These Objects are available for ready usage.
JSP Objects description
JSP object Servlet API Object Description
application javax.servlet.ServletCont Context
ext (Execution
environment) of
config javax.servlet.ServletConfi the
The Servlet.
g for the JSP.
exception java.lang.Throwable The exception
that resulted when
an error occurred.
out javax.servlet.jsp.JspWrite An object that
r writes into a JSP's
output stream.
JSP Objects description…
JSP object Servlet API Object Description
pageContext javax.servlet.jsp.PageContext Page context
for the JSP.
request javax.servlet.HttpServletRequ The client
est request.
response javax.servlet.HttpServletResponse The response
to the client.
session javax.servlet.http.HttpSessio Session
n object created
for requesting

page javax.servlet.Servlet Refers to

servlet object.
request object
•It provides access to data sent within a HTTP Request.
Cookie[] getCookies()
Enumeration getHeaderNames()
String getQueryString()
String getRemoteUser()
HttpSession getSession()
HttpSession getSession(boolean create)
String getRequestedSessionId()
boolean isRequestedSessionIdValid()
Enumeration getHeaderNames()
int getIntHeader(java.lang.String name)
String getHeader(String name)
boolean isRequestedSessionIdFromCookie()
boolean isRequestedSessionIdFromURL()
StringBuffer getRequestURL()
String getServletPath()
String getMethod()
String getContextPath()
Sample Program - 9
<%@ page language="java" contentType="text/html" %>

<html> <body bgcolor="white" >

The following information was received :

<li> Request Method : <%= request.getMethod() %>

<li> Request URI : <%= request.getRequestURI() %>
<li> Request Protocol : <%= request.getProtocol() %>
<li> Request Servlet Path : <%= request.getServletPath() %>
<li> Request Query String : <%= request.getQueryString() %>
<li> Request Sever Name : <%= request.getServerName() %>
<li> Request Port : <%= request.getServerPort() %>
<li> Request Address : <%= request.getRemoteAddr() %>
<li> Request Browser : <%= request.getHeader("User-Agent") %>
</body> </html>
•It allows setting of response message including html
Code, cookies, headers and other information.

void addCookie(Cookie cookie)

void addHeader( String name, String value)
void addIntHeader( String name, int value)
void setHeader( String name, String value)
void setIntHeader( String name, int value)
boolean containsHeader( String name)
void sendRedirect( String location)
String encodeRedirectURL(String url)
String encodeURL(String url)
void setStatus(int sc)
void setStatus(int sc, String sm)
Sample Program - 10
<html> <body>
<% Cookie cookies[] = request.getCookies();
boolean flag = false;
String name;
for( int i = 0; i < cookies.length; i++ )
name = cookies[ i ] .getName();
out.println( name + " : " + cookies[ i ].getValue( ) +
"<br>" );
if( name.trim().equals( "user_id" ) )
flag = true;
}catch( Exception e ){ System.out.println( e ); }
if( ! flag ) {
out.println( "No cookies found" );
response.addCookie( new Cookie( "user_id", "STEP" ) );
•It stores information for a particular user session.
•Data stored in a session object are not discarded when
the user jumps between pages in the application; they
persist for the entire user session.
•The web server destroys the session object when the
session is invalidated.

Object getAttribute( String name)

void setAttribute( String name, Object value)
Enumeration getAttributeNames()
void removeAttribute( String name)
void putValue( String name, Object value)
Object getValue( String name)
String[] getValueNames()
void removeValue( String name)
session object (Contd)

String getId()
long getCreationTime()
long getLastAccessedTime()
int getMaxInactiveInterval()
void setMaxInactiveInterval(int
ServletContext getServletContext()
HttpSessionContext getSessionContext()
void invalidate()
boolean isNew()

Sample Program - 11
<html> <body>
<% java.util.Enumeration attribute_names = session.getAttributeNames();
String attr_name, attr_value; boolean entires_found_flag = false;
if( attribute_names != null )
while( attribute_names.hasMoreElements() )
entires_found_flag = true;
attr_name = (String) attribute_names.nextElement();
attr_value = (String) session.getAttribute( attr_name.trim() );
out.println( "value of the attribute " + attr_name + " is " + attr_value + "<br>" );
if( entires_found_flag == false )
session.setAttribute( "attribute1", "value1" );
session.setAttribute( "attribute2", "value2" );
%> </body> </html>
Sample Program - 12
<FORM METHOD=POST ACTION="http://localhost:8080/aaa/B.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20>
</FORM> A.jsp

String name = request.getParameter( "username" );
session.setAttribute( "theName", name );
<HTML> <BODY> B.jsp
<A HREF="http://localhost:8080/aaa/C.jsp">Continue</A>

Hello, <%= session.getAttribute( "theName" ) %> C.jsp
application object
•Allows interaction with Servlet container/environment.
Object getAttribute(String name)
Enumeration getAttributeNames()
void removeAttribute( String name)
void setAttribute(java.lang.String name, Object object)
String getInitParameter(String name)
Enumeration getInitParameterNames()
String getServerInfo()
int getMajorVersion() int getMinorVersion()
String getMimeType( String file )
java.lang.String getRealPath(java.lang.String path)
Servlet getServlet(java.lang.String name)
Enumeration getServletNames()
Enumeration getServlets()
void log( Exception exception, String msg)
void log( String msg)
void log( String message, Throwable throwable)
String getServletContextName()
RequestDispatcher getRequestDispatcher(java.lang.String path) 70
Sample Program - 12
<h2>Display the default application settings</h2>

out.println( application.getServerInfo() + "<br><br>" );

java.util.Enumeration enum = application.getAttributeNames();

String element_name;
while( enum.hasMoreElements() )
element_name = (String) enum.nextElement();
out.println( "<b>" + element_name + "</b> ----------------" + application.getAttribute(
element_name ) + "<br>");

config object
It passes configuration information to a servlet when it
is instantiated.
The information includes initialization parameters and
the ServletContext object, which describes the context
within which the servlet is running.

String getInitParameter(String name)

Enumeration getInitParameterNames()
String getServletName()
ServletContext getServletConext()

Sample Program - 13
<html> <body>
java.util.Enumeration params = config.getInitParameterNames();
String name;
out.println( "<ul>" );
while( params.hasMoreElements() )
name = (String) params.nextElement();
out.println( "<li>" + name + "..." + config.getInitParameter( name.trim() )+ "</li>" );
out.println( "</ul>" );
</body> </html>

exception object
•It represents all errors and exceptions. It can
be accessed in a JSP page that is declared as an
error page using the isErrorPage attribute of the
page directive.

String getMessage()
String printStackTrace()
String toString()

out object
It defines an object for writing to JSP's output stream.

void clearBuffer()
void flush()
int getBufferSize()
int getRemaining()
boolean isAutoFlush()
void newLine()

void print(...)
void println(...)

pagecontext object
•It stores information local to a JSP.
•Each JSP has its own pageContext object that the
server creates when the user accesses the page
•It is deallocated when the user leaves the page.
Object findAttribute(String name)
void removeAttribute(String name)
void setAttribute(String name, Object attribute)
JspWriter getOut()
Object getPage()
ServletRequest getRequest()
ServletResponse getResponse()
ServletConfig getServletConfig()
ServletContext getServletContext()
HttpSession getSession()
Exception getException()
void forward(String path ) 
void include( String path)     
Sample Code
Object val = pageContext.findAttribute( pageContext.PAGE );
out.println( val + "<br>" );
val = pageContext.findAttribute( pageContext.APPLICATION );
out.println( val + "<br>" );
val = pageContext.findAttribute( pageContext.CONFIG );
out.println( val + "<br>" );
val = pageContext.findAttribute( pageContext.EXCEPTION );
out.println( val + "<br>" );
val = pageContext.findAttribute( pageContext.OUT );
out.println( val + "<br>" );
val = pageContext.findAttribute( pageContext.PAGECONTEXT );
out.println( val + "<br>" );

JSP Standard Action Tags
(XML format)
•They replace large sections of Java code.
•Standard actions are actions that must be
implemented by every JSP container.
•They perform actions such as instantiating
an object or changing an objects state.
•JSP actions are a technique to separate
business logic from presentation logic
(removes Java code from JSP).
•In reality, actions does not remove Java
code but hides Java code from JSP author. 78
JSP Action tags (Contd)

• Standard action tags start with

the namespace prefix jsp
followed by a colon and then by
tag name.
• Ex: <jsp:param>
• Actions may have attributes and
tag bodies.
Handling of Actions
•JSP translators treat action tags as
tokens that must be replaced with Java
•Code for actions are defined in a tag
•The translator simply replaces action
tags with output of the code that is
referenced by the action.
Handling of Actions…
• Ex: The tag
<jsp:useBean id=“test” class=“one.two.Tester”>

will be replaced with

Object test = (one.two.Tester)
“one.two.Tester” );

Action tags
• Following actions tags are available:
• <jsp:useBean>
• <jsp:getProperty>
• <jsp:setProperty>

• <jsp:param>
• <jsp:forward>
• <jsp:include>
• <jsp:plugin>
useBean action tag
•It is used to access a Java bean (not EJB) in a
JSP document.
•Causes container to find an existing instance
of the bean in the scope, with the specified id.
If object is not found in that scope, container
tries to create a new instance.
•The setProperty and getProperty action tags
are related to this tag.

<jsp:useBean attribute_name=attribute_value />
Attributes in useBean tag

Attribute Function
id Name used to refer the bean
within the page. Must be unique.
scope page/request/session/application.
class Fully qualified bean class name.
type Reference type (super class or
same type).

setProperty action tag
•It allows to set/assign a value for a bean
•Bean id must be created using useBean tag
before using setProperty and getProperty tags.
<jsp:setProperty attr_name=attri_val />

Attributes in setProperty tag
Attribute Description
name Bean id specified in useBean.
property •Name of the property to be set.
•If individual bean property is specified,
respective setter method will be invoked.
•If *, client request parameter with same
name as bean property will be used to set
the values.
param Client request parameter whose value
will be used to set the value.
value Value to be assigned to the property.
Attributes in setProperty tag

• The name and property

attributes are mandatory.
• param and value attributes are
mutually exclusive.
• If param and value are not used,
the tag attempts to use value of
the request parameter with same
getProperty action tag
•It allows to retrieve the value of a bean

<jsp:getProperty attr_name=attri_val />

name->bean id specified in useBean.
property-> property whose value is to

Bean access code 1 (bean)
package test;

public class StudentBean

{ test/
private int id;
private String name;

public StudentBean()
id = -1;
name = "---";
public int getId() { return id; }
public void setId( int student_id ) { id = student_id; }
public String getName() { return name; }
public void setName( String n ) { name = n; }
Bean access code 1 (JSP)
<jsp:useBean id="stBean" class="test.StudentBean" scope="page" />
<html> <body>
Details Before changing the bean
Student id : <jsp:getProperty name="stBean" property="id" />
Student name : <jsp:getProperty name="stBean" property="name" />
<br> <br> <br>
<jsp:setProperty name="stBean" property="id" value="101" />
<jsp:setProperty name="stBean" property="name" value="step_student"
Details After changing the bean
Student id : <jsp:getProperty name="stBean" property="id" />
Student name : <jsp:getProperty name="stBean" property="name" />
</body> </html>
Beans and Form processing

package test2;

public class UserData

String username;
String email;
int age;

public void setUsername( String value ){ username = value; }

public void setEmail( String value ){ email = value; }

public void setAge( int value ){ age = value; }

public String getUsername() { return username; }

public String getEmail() { return email; }

public int getAge() { return age; }


Beans and Form processing
<FORM METHOD=POST ACTION="beantest.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR>
What's your e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR>
What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4>

<jsp:useBean id="user" class="test2.UserData" scope="session"/>

<jsp:setProperty name="user" property="*"/> beantest.jsp

<HTML> <BODY> <A HREF=result.jsp>Continue</A> </BODY> </HTML>

<jsp:useBean id="user" class="test2.UserData" scope="session"/>

<HTML> <BODY> result.jsp
The following data were received by the client <BR>
Name: <%= user.getUsername() %><BR>
Email: <%= user.getEmail() %><BR>
Age: <%= user.getAge() %><BR>
Another Example

package test3;

public class User

private String id;
private String surname;

public void setId( String id ){ = id; }

public String getId(){ return id; }
public void setSurname( String surname ) { this.surname =
surname; }
public String getSurname( ){ return surname; }

Another Example
<jsp:useBean id="userA" class="test3.User" />

<jsp:setProperty name="userA" property="surname" value="Smith" />

<jsp:setProperty name="userA" property="id" value="<%= 32 + 45 + "45" %>" />

Your data are as follows : <br>

ID : <jsp:getProperty name="userA" property="id" />

SURNAME : <jsp:getProperty name="userA" property="surname" />

include action tag
• It allows embedding of another page within
the current jsp.
• Included components must be valid JSP pages
or servlets.
• Note: Included file is not allowed to modify
response headers, nor to set cookies in the

• Syntax:
page->file (Mandatory)
flush->true/false (Optional)
How include action works
1. Original JSP file stops processing and
passes the request to included file.
2. The included file generates its
3. Response of the included file is
returned to the calling JSP, which
proceeds with its processing and
generates the final response.
Sample Code
<HEAD><TITLE>Example Of The include Action</TITLE></HEAD>

Include the First File
<jsp:include page="test1.jsp" />
Include the Second File:
<jsp:include page="test2.jsp" />


forward action tag
• It is used to transfer the control to another
JSP, HTML or servlet.
• It permanently transfers processing from one
JSP to another on the local server.
• Any content generated by the original page is
discarded and processing begins anew at the
second JSP.

• Syntax:
How forward action works
• Original JSP file stops processing and
passes the request to forwarded
• Forwarded component generates the
final response.

• Note:
– Execution never returns to the calling page.
– Only one effective forward action is valid in
a JSP document, later forward actions are
Sample Code

<HEAD><TITLE>Example Of The forward Action</TITLE></HEAD>

<% if (Math.random() > .5)

{ %>
<jsp:forward page=“one.jsp" />
<% } else
{ %>
<jsp:forward page="two.jsp" />
<% } %>
<%= System.getProperties() %>

param action tag
• It is used in conjunction (as a sub-tag) with
include or forward action.
• It is used to pass parameters to the resource
being included/forwarded.
• In the included/forwarded resource these
parameters can be accessed using getParameter()
• Syntax:
<jsp:include …..>
plugin action tag
• It is used to embed objects for execution on
• It is similar to <applet> tag
• Syntax:
<jsp:plugin type->applet/bean
code->class name
width->width height->height
archive->archive list
/> 102
• Directives give instructions to the JSP
container to be interpreted at translation
The general Syntax:
<%@ directivename attribute=“value”

• There are 3 directives

– The page directive
– The include directive
– The taglib directive 103
Page Directive
Defines attributes applicable to the entire JSP page.
– <%@ page atribute_name=attribute_value %>
– Possible attributes
• language=“java”
• extends=“package.class”
• import=“package.*, package.class,…”
• session=“true”
• buffer=“8kb”
• autoFlush=“true”
• isThreadSafe=“true”
• info=“text”
• errorPage=“relativeURL”
• isErrorPage=“false”
• contentType=“mimeType”
• pageEncoding=encoding
Note: The extends attribute is recommended not to be used.
Page Directive - Details
Attribute Value Default Example
info Text string None info=“Registration form”
language Scripting lang “java” language=“java”

contentType MIME type, “text’html” contentType=“text/java”

extends Class name None extends=“com.gui.MyGUI”

import Packages(s) None import=“”
multiple imports separated by “,”
session Boolean flag “true” session=“true”
buffer Size or none Server specific buffer=“12kb” buffer=“false”
autoFlush Boolean flag “true” autoFlush=“false”
isThreadSafeBoolean flag “true” isTheadSafe=“true”
errorPage Local URL None errorPage=“msg/failed.jsp”
isErrorPage Boolean flag “false” isErrorPage=“false”
Sample code
<%@page info="jaa re bakra" %>

<%= getServletInfo() %>


<html> <body>
<%= "hello" %>
<%@page info="haal chaal kya khabar" %>
<%= getServletInfo() %>

</body> </html>

Handling Exceptions using
<html> <body>
well come to error test
<%@page errorPage="error.jsp" %>

<% int x = 10, y = 0; error_test.jsp

out.println( x/y );
out.println( "all is well" );
</body> </html>

<html> <body>
Hai how r u
<%@page isErrorPage="true" %>
<br> error.jsp
<% out.println ( "error " + exception ); %>
<br/> <br/>
Hello am fine
</body> </html>
include Directive
• Used to include a specified file's content
into this page at translation time.
• If the included file content changes, it
is not reflected until server is restarted
or until the main JSP file changes.
• Only static pages are recommended to
be included.
• Syntax:
<%@ include file=“file_name" %>
Sample Code
Hi, How r u
<%@ include file="one.jsp" %> two.jsp
Hi, am doing fine

<%= "Hello World" %>
</b> one.jsp
<%= "Hello World" %>
include directive vs
include action

directive action
Included at JSP Included at JSP
translation time. request time.
Inclusion is static Inclusion is
in nature. dynamic.
Recommended for Web component
static/template usage
data. recommended.
Cannot pass Can pass
parameters. parameters using 110
Tag libraries
<taglib> directive
Tag Libraries
• JSP Tags can be of two types:
– Predefined tags: They have jsp: as
prefix. Ex: jsp:include.
– Custom tags: They are external,
user defined tag library.
• The ability to define custom tags
were made possible in JSP 1.1
Tag Library
• It is a collection of custom actions/tags,
included in a JSP page.
• Defining custom tags involve:
– Development of tag handlers for the tag.
– Declaration of tag in tag library descriptor.
• A tag library defines a set of related, custom
tags and links them to objects (tag handlers)
that implements functionality for the tags.
• JSP container uses TLD to interpret/handle
taglib directives inside JSP documents. 113
Advantages of Tag Library
• Custom tags allow a convenient way to
provide extension of JSP functionality.
• Role segregation:
• Tag libraries are created by Java
developers which will be used by Web
application designers. Hence division of
labor between library developers and
library users.
• Enhanced productivity by hiding
implementation details and encapsulating
redundant code. 114
taglib Directive
•It allows us to access user-defined/custom
tags in a JSP.
<%@ taglib
uri=“tld uri”
prefix=“unique name”

•Both attributes are mandatory.

•More than one taglib directive can be used
in the same JSP.
Attribute uri
• TLD files are stored in WEB-INF directory of WAR or
in a subdirectory of WEB-INF.
• You can reference a TLD directly or indirectly. Ex:
– Direct reference
• <%@ taglib uri="/WEB-INF/one.tld" prefix="tt"
– Indirect reference (uses a short logical name)
• <%@ taglib uri="/aab" prefix="tt" %>
• Logical name is mapped to absolute location in
deployment descriptor using following entries:
Custom tags and TLD
•Custom tags are accessed in the JSP
document using prefix name followed
by the tag name.
•Prefix names uniquely identify tags
in spite of tag namespace reuse in
different tag libraries.
•A prefix can not be java, javax, jsp,
jspx, servlet, sun and sunw. 117
Custom tags and TLD
• Container takes necessary action when
custom tag is encountered.
• When a JSP page containing a custom
tag is translated into a servlet, the tag
is converted to operations on the
respective tag handler.
• The web container then invokes those
operations when the JSP page’s servlet
is executed.
TLD format
<?xml version="1.0">
<tlib-version> version (M) </tlib-version>
<jsp-version> compatible jsp version (O) </jsp-version>
<short-name> document name (M) </short-name>
<uri> Unique string (O) </uri>
<display-name>name in visual tools (O) </display-name>
<small-icon>small icon in visual tools (O) </small-icon>
<large-icon>large icon in visual tools (O) </large-icon>
<description> Description (O) </description>
<tag>------------ </tag>
<tag>------------ </tag>
</taglib> 119
TLD format
<name> unique tag name (M) </name>
<tag-class> tag handler class (M) </tag-class>
<tei-class> TagExtraInfo class (O) </tei-class>
<body-content> Can be one of the following:
empty/JSP/tagdependent (O)
<display-name>name in visual tools (O) </display-name>
<small-icon>small icon in visual tools (O) </small-icon>
<large-icon>large icon in visual tools (O) </large-icon>
<description> Description (O) </description>
<variable> scripting variable (O) </variable>
<attribute> (O)
<name> attribute name (M) </name>
<required> boolean value (O) (default -> false) </required>
<rtexprvalue> boolean value (O) (default-> false) </rtexprvalue>
<type>fully qualified data type of the attribute (O) </type>
<attribute>..... </attribute>
<attribute>..... </attribute>
</tag> 120
TLD Tag Description
General Description elements/tags
Tag Description
<tlibversion> Version number of library. (Must)
<jspversion> Compliant JSP version.
<shortname> Simple default name. Preferred prefix
value in taglib directive. (Must)
<uri> Unique uri of the TLD document.
<description> Description/comments about TLD.
<tag> Contains elements describing the tag.
TLD Tag Description
Tags within the <tag> tag.
Tag Description
<name> Name of the tag
<tag-class> Full class name of tag handler.
<tei-class> Subclass of TagExtraInfo.
<body- Specifies whether tag can have content.
content> Can be one of the following:
tagdependent :- contains non-jsp code.
JSP :- body contains JSP code.
empty :- no body for this tag.
<variable> Scripting variable information.
<attribute> Defines attributes for the tag. 122
TLD Tag Description
Tags within the <attribute> tag.
Tag Description
<name> Defines attribute name.
<required> Specifies whether attribute is optional
or not. (default – false)
Values - true/false/yes/no
<rtexprvalue> Specifies whether the attribute value
can be run time expression or static.
Values - true/false/yes/no
<type> Specifies fully qualified data type.
(Static values are always of type
String). 123
TLD Tag Description
Tags within the <variable> tag.
Tag Description
<name-given> The variable name as a constant.
<name-from- Attribute name whose translation-time
attribute> value will give name of the variable.
One among name-given or
name-from-attribute is mandatory.
<variable-class> Fully qualified class name (type) of the
variable. java.lang.String is default.
<declare> Whether the variable refers to a new
object. True is default.
<scope> Scope of variable. NESTED is default.
TLD Tag Description
Possible values for <scope> tag within <variable> tag

Value Availability Methods

NESTED Between start tag and In doInitBody and
end tag doAfterBody if tag
handler implements
BodyTag; otherwise, in
AT_BEGIN From start tag until doInitBody,
end of the page doAfterBody &
doEndTag id tag
handler implements
BodyTag; otherwise, in
AT_END After end tag until end doStartTag &
In doEndTag.
of the page doEndTag.
Code – tld file
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD
JSP Tag Library 1.2//EN"

<description>Gets the current System
</taglib> 126
Code – Java class
package test;

import java.util.Date;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class DateClass extends TagSupport

public int doEndTag() throws JspException
Date dt = new Date();
String dt_str = "" + dt;
pageContext.getOut().write( dt_str );

}catch( Exception e) { System.out.println( e ); }

return EVAL_PAGE;
Code – Jsp file

<%@ page language="java" %>

<%@ taglib uri="CurrentDate.tld" prefix="date" %>
<h1> The date & time now is : <date:today /> </h1>

Tag types
Simple Tags
• A simple tag contains no body and no
• Ex: <prefix_name:tag_name />

• It would have the following entry in the

respective TLD:

Tags With Attributes
• A custom tag can have attributes listed in
start tag having syntax attr="value".
• Attributes customize behavior of a custom
tag just as parameters customize the
behavior of a method.
• Attribute value can be a String constant or
a runtime expression. Ex:
4.<prefix_name:tag_name attr=“val" />
attrib2="val" />
Tags with Bodies
• A custom tag can contain custom and core
tags, scripting elements, HTML text, and tag-
dependent body content between the start
and end tag.
• Ex:
<prefix_name:tag_name attrib_name="val" />
<% cart.clear(); %>
<font color="#ff0000" size="+2"><strong>
You just cleared your shopping cart!
</prefix_name:tag_name> 132
Tags That Define Scripting
• A custom tag can define a variable that
can be used in scripts within a page.

1)<tt:lookup id="tx" type="UserTransaction"

name="java:comp/UserTransaction" />
<% tx.begin(); %>

2) <tt:define id="book" name="bookDB" />

<jsp:getProperty name="book" property="title">

Cooperating Tags
• Custom tags can cooperate with each
other through shared objects. In the
following example, tag1 creates an object
called obj1, which is then reused by tag2.
<tt:tag1 attr1="obj1" value1="value" />
<tt:tag2 attr1="obj1" />

• Also an object created by enclosing tag is

available to all inner tags.
<tt:innerTag />
Tag Handlers
• It is a Java class that implements behavior
of a custom tag.
• It is invoked by Web container to evaluate
a custom tag during execution of JSP page
that references the tag.
• They must implement either Tag or
BodyTag interface, preferably via
TagSupport and BodyTagSupport classes
• Tag handlers will be referenced in TLD
files. 135
Tag Handlers…
• Tag handlers have access to an API that
allows it to communicate with the JSP
• Entry point to the API is PageContext,
through which a tag handler can
retrieve all implicit objects accessible
from a JSP page.

Interface Hierarchy

•It defines a handler for simple tags
which does not manipulate tag body.
•It specifies a framework (protocol) for
interaction between a Tag handler and
JSP page implementation class.
• i.e. it defines the life cycle methods to
be invoked at start and end tag.
•It specifies accessor methods for
pageContext and parent properties. 139
Tag – Method summary
void setPageContext(PageContext pc)
void setParent(Tag t)
int doStartTag()
int doEndTag()
Tag getParent()
void release()

• JSP page implementation object invokes

setPageContext and setParent, in that
order, before invoking doStartTag() or
Tag - Field Summary
• static int SKIP_BODY
Skip body evaluation.
• static int EVAL_BODY_INCLUDE
Evaluate the tag body.

• static int SKIP_PAGE

Skip the rest of the page.
• static int EVAL_PAGE
Continue evaluating the page.
Tag - Field usage
•If the TLD file indicates that the action tag
must be empty, then doStartTag() must
return SKIP_BODY.
•Otherwise, the doStartTag() method may
•If SKIP_BODY is returned and if body is
present, body is not evaluated.
•If EVAL_BODY_INCLUDE is returned, the
body is evaluated and "passed through" to
the current out. 142
Sample code
A simple tag for example <abc:simple /> would be
implemented by the following tag handler:

public SimpleTag extends TagSupport

public int doStartTag() throws JspException
try {
} catch (Exception ex)
pageContext.getOut().print("SimpleTag: " +
ex.getMessage()); }
return SKIP_BODY;
public int doEndTag() { return EVAL_PAGE; } 143
• It extends Tag by defining one additional
method ( doAfterBody() ) that processes tag
• The doAfterBody() is invoked after body
evaluation iff doStartTag() returns
• If it returns EVAL_BODY_AGAIN, then the
body will be reevaluated.
• If it returns SKIP_BODY, then the body
reevaluation will be skipped and
doEndTag() is invoked. 144
IterationTag Members

Field Summary
• static int EVAL_BODY_AGAIN
Request reevaluation of
body content.

Method Summary
• int doAfterBody()
Process body content. 145
• It extends IterationTag and defines
additional methods that let a tag handler
to manipulate body content by providing

• While implementing BodyTag, the

doStartTag() can return SKIP_BODY,
•If EVAL_BODY_BUFFERED is returned,
then a BodyContent object will be created
by the container to encapsulate the body.

•The container creates BodyContent

object by calling pushBody() of the
current pageContext.

•The container returns this object to JSP

by calling popBody() of the PageContext.
Field Summary
Request the creation of new buffer, a
BodyContent on which to evaluate the
body of this tag.
Deprecated as of Java JSP API 1.2, use
Method Summary
void setBodyContent(BodyContent b)
Sets the bodyContent.
It will be invoked by container.

void doInitBody()
Action method to handle body evaluation.
Invoked after setBodyContent().

Both methods will be invoked only if doStartTag()

BodyTag - Field usage
•If TLD file indicates that action must be
empty, then doStartTag() must return

•Otherwise, doStartTag() may return


•If SKIP_BODY is returned, body is not

evaluated and doEndTag() is invoked. 150
BodyTag - Field usage…
•If EVAL_BODY_INCLUDE is returned, the body
is evaluated and "passed through" to current
out, doAfterBody() followed by doEndTag() is

•If EVAL_BODY_BUFFERED is returned,

setBodyContent() followed by doInitBody() is
invoked, the body is evaluated, doAfterBody()
followed by doEndTag() is invoked.
Interface TryCatchFinally
•It provides optional support for tag handlers
implementing Tag, IterationTag or BodyTag.
Method Summary
void doCatch( Throwable t )

Will be invoked if a Throwable occurs while

evaluating BODY.
void doFinally()
Will be invoked in all cases after doEndTag() for
any class implementing Tag, IterationTag or
BodyTag. 152
Class Hierarchy

Class TagSupport
• Is a utility class to be extended by new tag
handlers instead of implementing
• It implements Tag and IterationTag and
adds additional methods including getter
methods for the properties in Tag.
• It is further extended by BodyTagSupport.
• It has one static method that facilitates
coordination among cooperating tags. 154
Field Summary
• protected String id
• protected PageContext pageContext

Fields inherited from Tag


Fields inherited from IterationTag

Method Summary
• int doStartTag()
Default processing of start tag.
• int doEndTag()
Default processing of end tag.
• int doAfterBody()
Default processing for a body.

• static Tag findAncestorWithClass(Tag from, Class

Find instance of given type closest to given tag.

• String getId()
The value of the id attribute of this tag; or null.
• void setId(String id)
Set the id attribute for this tag. 156
Method Summary…
• Tag getParent()
The Tag instance most closely enclosing this tag
• void setParent(Tag t)
Set the nesting tag of this tag.

• Object getValue(String k)
Get a the value associated with a key.
• Enumeration getValues()
• void setValue(String k, Object o)
• void removeValue(String k)

• void setPageContext(PageContext pageContext)

• void release() 157

Class BodyTagSupport
• A base class for defining tag handlers
implementing BodyTag.
• It implements BodyTag, IterationTag,
Serializable and Tag interfaces
• It adds additional methods including
getter methods for bodyContent
property and methods to get the
previous out (JspWriter).
Field Summary
• protected BodyContent bodyContent
Fields inherited from TagSupport
• Id
• pageContext
Fields inherited from interface Tag
Fields inherited from interface IterationTag
Fields inherited from interface BodyTag
• EVAL_BODY_TAG (Deprecated)
Method Summary
• int doStartTag()
Default processing of start tag.
• void setBodyContent(BodyContent b)
Prepare for evaluation of the body; store
• void doInitBody()
Prepare for body evaluation just before first body
• int doAfterBody()
After body evaluation.
• int doEndTag()
Default processing of the end tag. 160
Method Summary…
• BodyContent getBodyContent()
Get current bodyContent.
• JspWriter getPreviousOut()
Get the out (JspWriter).
• void release()

Class BodyContent
• It extends JspWriter.
• It encapsulates evaluated body content.
• Since it encapsulates the result of
evaluation, it will not contain actions and
the like, but the result of their invocation.
• Its buffer size is unbounded.
• A BodyContent is made available to a
BodyTag through a setBodyContent() call.
• Tag handlers can use it until after the call
to doEndTag(). 162
Method Summary
• protected BodyContent(JspWriter e)

• void clearBody()
• abstract getReader()
Return value of this BodyContent as a Reader.
• abstract String getString()
Return value of the BodyContent as a String.
• abstract void writeOut( out)
Write contents of this BodyContent into a
Class TagExtraInfo
• Optional class specified in the TLD to
describe additional translation-time
information not described in the TLD.
• TagExtraInfo class must be mentioned
in TLD file.
• This class can be used:
– to indicate that the tag defines scripting
– to perform translation-time validation of
the tag attributes.
Method Summary
• TagInfo getTagInfo()
Get the TagInfo for this class.
• VariableInfo[] getVariableInfo(TagData data)
information on scripting variables defined by
the tag associated with this TagExtraInfo
• boolean isValid(TagData data)
Translation-time validation of the attributes.
• void setTagInfo(TagInfo tagInfo)
Set the TagInfo for this class.
Class TagInfo
• Tag information for a tag in a Tag
Library; This class is instantiated from
the TLD and is available only at
translation time.

Field Summary
• static String BODY_CONTENT_EMPTY
static constant for getBodyContent() when it
is empty
• static String BODY_CONTENT_JSP
static constant for getBodyContent() when it
is JSP
• static String
static constant for getBodyContent() when it
is Tag dependent
Method Summary
• String getTagName()
• String getTagClassName()
• TagExtraInfo getTagExtraInfo()
The instance (if any) for extra tag information
• String getBodyContent()
• String getDisplayName()
• String getSmallIcon()
• String getLargeIcon()
• String getInfoString() 168
Method Summary…
• TagAttributeInfo[] getAttributes()
• TagVariableInfo[] getTagVariableInfos()

• TagLibraryInfo getTagLibrary()

• boolean isValid(TagData data)

Translation-time validation of attributes.

Class VariableInfo
• Provides information about scripting
• This information is provided by
TagExtraInfo classes and it is used during
translation of JSP.

Member summary
Field Summary
• static int AT_BEGIN
• static int AT_END
• static int NESTED

Method Summary
• String getVarName()
• String getClassName()
• boolean getDeclare()
• int getScope()
Class TagVariableInfo
• Provides scripting variable information for
a tag in a Tag Library.
• This class is instantiated from the TLD and
is available only at translation time.
• This information is only available in

Method Summary
• String getNameGiven()
• String getNameFromAttribute()
• String getClassName()
• boolean getDeclare()
• int getScope()

Class TagAttributeInfo
• Provides information about attributes of a
Tag, available at translation time.
• This class is instantiated from TLD file.
• Only the information needed to generate
code is included here.

Method Summary

• String getName()
• boolean isRequired()
• boolean canBeRequestTime()
• String getTypeName()

Class TagLibraryInfo
• Translation-time information associated
with a taglib directive, and its
underlying TLD file. Most of the
information is directly from the TLD,
except for the prefix and the uri values
used in the taglib directive.

Field Summary
• protected String tlibversion
• protected String jspversion
• protected String shortname
• protected String uri
• protected String info

• protected TagInfo[] tags

Method Summary
• String getRequiredVersion()
• String getShortName()
• String getURI()
• String getInfoString()

• TagInfo getTag(java.lang.String shortname)

• TagInfo[] getTags()

Class PageData
•Provides information about the JSP page during
translation time.
•Information corresponds to XML view of JSP
page contents.
•It is instantiated and used by the container.

Method Summary
abstract InputStream getInputStream()
Returns input stream on the XML view (include
directives will be expanded) of a JSP page. 179
Class TagAttributeInfo
•Provides information about Tag attributes,
available at translation time.
•It is instantiated using information in the TLD

Field Summary
static String ID "id" is wired in to be ID.
Constructor Summary
TagAttributeInfo( String name, boolean
required, String type, boolean reqTime)
Method Summary
boolean canBeRequestTime()
Determines whether this attribute can hold a request-time
static TagAttributeInfo getIdAttribute(TagAttributeInfo[] a)
Convenience static method that goes through an array of
TagAttributeInfo objects and looks for "id".
String getName()
The name of this attribute.
String getTypeName()
The type (as a String) of this attribute.
boolean isRequired()
Whether this attribute is required.
Class TagData
Provides information about attribute/value for a
tag instance at translation-time only.
•It is only used as an argument to isValid() and
getVariableInfo() of TagExtraInfo, which are
invoked at translation time.

Object getAttribute(String attName)

Enumeration getAttributes()
String getAttributeString(String attName)
void setAttribute( String attName, Object value)
Writing Tag Handlers

Simple tags
• Handler for simple tag must implement
doStartTag and doEndTag methods of Tag
• Method doStartTag is invoked when the start
tag is encountered.
• Method doStartTag must return SKIP_BODY
since simple tags have no body.
• Method doEndTag is invoked when the end
tag is encountered.
• Method doEndTag needs to return EVAL_PAGE
if the rest of the page needs to be evaluated;
otherwise, it should return SKIP_PAGE. 184
Simple tag - Example
A simple tag <tt:simple /> would be implemented by the
following tag handler:

public SimpleTag extends TagSupport {

public int doStartTag() throws JspException {
try {
} catch (Exception ex) {
throw new JspTagException("SimpleTag: " +
return SKIP_BODY;
public int doEndTag() { return EVAL_PAGE; }
} 185
Tags with Attributes
• In this case for each attribute, the Tag
Handler must define a property as well as get
and set methods that conform to JavaBeans
architecture conventions.
• Ex: Tag handler for following tag in JSP,
<prefix:tag_name parameter="Clear">
contains the following declaration and methods:
private String parameter = null;
public String getParameter()
{ return parameter; }
public void setParameter(String parameter)
{ this.parameter = parameter; } 186
Attribute Validation
• The tag library documentation should describe
valid values for tag attributes.

• During JSP translation, container enforces

constraints contained in TLD for each attribute.

• Attributes passed to a tag can also be validated

during translation using isValid method of a class
derived from TagExtraInfo.

• Method isValid is passed a TagData object, which

contains information about each attribute.
Attribute Validation using
• The tag <tt:twa attr1="value1"/> has the following
TLD attribute element:
• This declaration indicates that the value of attr1
can be determined at runtime.
• The following isValid method checks that the value
of attr1 is a valid Boolean value.
Attribute Validation…
public class TEI extends TagExtraInfo
public boolean isValid(Tagdata data)
Object o = data.getAttribute("attr1");
if (o != null )
if ( ((String)o).toLowerCase().equals("true") )
return true;
return false;
} else
return false;
} 189
Tags with Bodies
• A tag handler for a tag with body is
implemented differently depending on
whether the tag handler needs to
interact with the body or not.

• A tag is said to interact with body

content if the tag handler
reads/modifies body content.

Tag Handler Does Not
Interact with Body
•If tag handler does not need to interact with
body, it should implement Tag interface or
extend TagSupport.
•If tag body needs to be evaluated, doStartTag
method must return EVAL_BODY_INCLUDE;
otherwise it should return SKIP_BODY.

•If a tag handler needs to iteratively evaluate

the body, it should implement IterationTag or
extend TagSupport.
•It should return EVAL_BODY_AGAIN from the
doStartTag and doAfterBody methods if the
body needs to be evaluated again. 191
Tag Handler Interacts with Body
• If tag handler needs to interact with body, it must
implement BodyTag or extend BodyTagSupport.
• Such handlers implement doInitBody and
• These methods have access to BodyContent object,
which provides several methods to read and write
• A tag handler can use BodyContent's getString or
getReader methods to extract body information and
writeOut(out) to write the body contents to out
• The parameter supplied to writeOut method is
obtained using tag handler's getPreviousOut
• This method ensures that a tag handler's results192are
Tag Handler Interacts with
doInitBody Method
• It is called before body content is evaluated and
hence is generally used to perform any initialization
that depends on body content.
doAfterBody Method
• It is called after the body content is evaluated.
• Like doStartTag method, doAfterBody must return an
indication of whether to continue evaluating body.
• Thus, if body should be evaluated again, doAfterBody
should return EVAL_BODY_BUFFERED; otherwise, it
should return SKIP_BODY.
release Method
• A tag handler should release any private resources in
the release method. 193
Tag Handler Interacts with
• The tag handler below reads body content (which contains
a SQL query) and executes the query. Since body does not
need to be reevaluated, doAfterBody returns SKIP_BODY.
public class QueryTag extends BodyTagSupport
public int doAfterBody() throws JspTagException
BodyContent bc = getBodyContent();
String query = bc.getString();
try {
Statement stmt = connection.createStatement();
ResultSet result = stmt.executeQuery(query);
} catch (SQLException e)
{ throw new JspTagException("QueryTag: " + e);
return SKIP_BODY;
Tag Handler Interacts with
body-content Element
• For tags that have a body, body content type must be
specified using body-content element:
• Body content containing custom/core tags, scripting
elements, and HTML text is categorized as JSP.
• All other types of body content--for example--SQL
statements would be labeled tagdependent.

Note: Value of body-content element does not affect

body interpretation by tag handler; It is only intended
to be used by an authoring tool for body content. 195
Thank You