Professional Documents
Culture Documents
1
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
language.
•JSP program files have an extension .jsp
2
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.
3
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.
5
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.
6
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
extension.
• JSP soon followed, with the first draft
API specifications appearing in 1998.
7
JSP History
12
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 java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
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.
15
JSP functionality
architecture
Web Server
JSP Page
qu est Translation by
Re JSP engine
Re
sp Compiled Servlet
on
se
Instantiation
Servlet is loaded to
server
16
JSP life cycle
• jspInit()
• jspDestroy()
• _jspService( request, response )
_jspService(request,response) jspDestroy()
jspInit()
Handle Requests: Invoked by
Initialise JSP
invoked container
Invoked only once
for every request to cleanup
17
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
environment).
– 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
19
Interface
javax.servlet.Servlet
•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()
• abstract String
getSpecificationVersion()
Return version of the JSP
specification supported by this JSP
engine.
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.
26
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.
• 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 java.io.Writer.
• 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)
35
Tag convention
• JSP tags usage is similar to those of
HTML tags:
– They begin and end with angle
brackets.
2. <jsp:useBean id="login“
class="UserBean">
<jsp:setProperty name="login“
property="group“
value="admin"/>
</jsp:useBean>
40
Components of a JSP program
• HTML code
• Comments
• JSP tags
• JSP Implicit Objects
• Java Beans
41
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 -->
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 %>
•Scriptlets
•To embed java code blocks
•format: <% code block %>
43
JSP tag types…
•Directives
• To specify information that affect
the whole JSP program
• format: <%@ directive_type
directive_attribute
%>
•Action tags
•Used to work with standard objects
•format:
<jsp:action_name action_attributes /> or
<jsp:action_name action_attributes> …
</jsp:action_name> 44
General rules
• JSP tags are case sensitive
<html>
<head>
<title>
My first JSP program
</title>
</head>
<body>
<b>
The Current system date is : <h1> <%= new java.util.Date() %>
</h1>
</b>
</body>
</html>
46
Deploying JSP’s on TOMCAT
47
Deploying JSP’s on J2EE RI
Server
48
Deploying JSP’s on Weblogic
49
Deploying JSP’s on JRun
50
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" ) %>
<br>
Os Name : <%= System.getProperty( "os.name" ) %>
<br>
User Name : <%= System.getProperty( "user.name" ) %>
<br>
User Home : <%= System.getProperty( "user.home" ) %>
<br>
User Directory : <%= System.getProperty( "user.dir" ) %>
<br>
</body> </html>
52
Sample Program - 4
•Simple usage of page directive, scriplet and
expression tags.
<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>
56
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++ ) { %>
<tr>
<td> <%= items[ i ] %> </td>
<td> <%= quantity[ i ] %> </td>
<td> <%= quantity[ i ] * cost[ i ] %> </td>
</tr>
<% } %>
</table>
</body> </html>
57
Control statements in JSP
Sample Program - 8
•Another example of using for loops
<html> <body>
<center>
<% 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];
%>
<% } %>
</center>
</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.
59
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.
ServletConfig
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.
60
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
client.
String getId()
long getCreationTime()
long getLastAccessedTime()
int getMaxInactiveInterval()
void setMaxInactiveInterval(int
interval)
ServletContext getServletContext()
HttpSessionContext getSessionContext()
void invalidate()
boolean isNew()
67
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>
68
Sample Program - 12
<HTML> <BODY>
<FORM METHOD=POST ACTION="http://localhost:8080/aaa/B.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20>
<P><INPUT TYPE=SUBMIT>
</FORM> A.jsp
</BODY> </HTML>
<%
String name = request.getParameter( "username" );
session.setAttribute( "theName", name );
%>
<HTML> <BODY> B.jsp
<A HREF="http://localhost:8080/aaa/C.jsp">Continue</A>
</BODY></HTML>
<HTML><BODY>
Hello, <%= session.getAttribute( "theName" ) %> C.jsp
</BODY></HTML>
69
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
<HTML> <BODY>
<h2>Display the default application settings</h2>
<%
out.println( application.getServerInfo() + "<br><br>" );
71
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.
72
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>
73
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()
74
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(...)
75
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)
76
Sample Code
<html><body>
<%
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>" );
%>
</body></html>
77
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)
81
Action tags
• Following actions tags are available:
• <jsp:useBean>
• <jsp:getProperty>
• <jsp:setProperty>
• <jsp:param>
• <jsp:forward>
• <jsp:include>
• <jsp:plugin>
82
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.
Syntax:
<jsp:useBean attribute_name=attribute_value />
83
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).
84
setProperty action tag
•It allows to set/assign a value for a bean
property.
•Bean id must be created using useBean tag
before using setProperty and getProperty tags.
•Syntax:
<jsp:setProperty attr_name=attri_val />
Attributes:
name
property
param
value
85
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.
86
Attributes in setProperty tag
•Syntax:
<jsp:getProperty attr_name=attri_val />
Attributes:
name->bean id specified in useBean.
property-> property whose value is to
retrieved.
88
Bean access code 1 (bean)
package test;
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; }
}
89
Bean access code 1 (JSP)
<jsp:useBean id="stBean" class="test.StudentBean" scope="page" />
<html> <body>
Details Before changing the bean
<br>
Student id : <jsp:getProperty name="stBean" property="id" />
<br>
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
<br>
Student id : <jsp:getProperty name="stBean" property="id" />
<br>
Student name : <jsp:getProperty name="stBean" property="name" />
</body> </html>
90
Beans and Form processing
package test2;
91
Beans and Form processing
<HTML> <BODY>
<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>
test.html
<P><INPUT TYPE=SUBMIT>
</FORM></BODY> </HTML>
package test3;
93
Another Example
<jsp:useBean id="userA" class="test3.User" />
94
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
response.
• Syntax:
<jsp:include
page->file (Mandatory)
flush->true/false (Optional)
95
How include action works
1. Original JSP file stops processing and
passes the request to included file.
2. The included file generates its
response.
3. Response of the included file is
returned to the calling JSP, which
proceeds with its processing and
generates the final response.
96
Sample Code
<HTML>
<HEAD><TITLE>Example Of The include Action</TITLE></HEAD>
<BODY>
Include the First File
<jsp:include page="test1.jsp" />
<BR>
Include the Second File:
<jsp:include page="test2.jsp" />
</BODY> </HTML>
97
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:
<jsp:forward
page->url
/>
98
How forward action works
• Original JSP file stops processing and
passes the request to forwarded
component.
• 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
ignored.
99
Sample Code
<HTML>
<HEAD><TITLE>Example Of The forward Action</TITLE></HEAD>
<BODY>
100
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()
method.
• Syntax:
<jsp:include …..>
<jsp:param
name->name
value->value
>
.
.
</jsp:include>
101
plugin action tag
• It is used to embed objects for execution on
client
• It is similar to <applet> tag
• Syntax:
<jsp:plugin type->applet/bean
code->class name
codebase->codebase
width->width height->height
align->alignment
archive->archive list
nspluginurl->url
iepluginurl->url
/> 102
Directives
• Directives give instructions to the JSP
container to be interpreted at translation
time.
The general Syntax:
<%@ directivename attribute=“value”
attribute=”value”%>
<html> <body>
<!--
<%= "hello" %>
<%@page info="haal chaal kya khabar" %>
-->
<%= getServletInfo() %>
</body> </html>
106
Handling Exceptions using
errorPage
<html> <body>
well come to error test
<%@page errorPage="error.jsp" %>
<html> <body>
Hai how r u
<br/>
<%@page isErrorPage="true" %>
<br> error.jsp
<% out.println ( "error " + exception ); %>
<br/> <br/>
Hello am fine
</body> </html>
107
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" %>
108
Sample Code
<html>
<body>
Hi, How r u
<%@ include file="one.jsp" %> two.jsp
Hi, am doing fine
</body>
</html>
<html>
<body>
<b>
<%= "Hello World" %>
</b> one.jsp
<h1>
<%= "Hello World" %>
</h1>
</body>
</html>
109
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
111
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
112
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.
•Syntax:
<%@ taglib
uri=“tld uri”
prefix=“unique name”
%>
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.1</jsp-version>
<short-name>dt</short-name>
<description>Gets the current System
date</description>
<tag>
<name>today</name>
<tag-class>test.DateClass</tag-class>
</tag>
</taglib> 126
Code – Java class
package test;
import java.util.Date;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
128
Custom
Tag types
129
Simple Tags
• A simple tag contains no body and no
attributes.
• Ex: <prefix_name:tag_name />
130
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" />
5.<prefix_name:tag_name
attr1="<%=bookDB.getBooks()%>"
attrib2="val" />
131
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!
</strong><br> <br></font>
</prefix_name:tag_name> 132
Tags That Define Scripting
Variables
• A custom tag can define a variable that
can be used in scripts within a page.
133
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" />
136
Package
javax.servlet.jsp.tag
ext
137
Interface Hierarchy
138
Tag
•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()
Field Summary
• static int EVAL_BODY_AGAIN
Request reevaluation of
body content.
Method Summary
• int doAfterBody()
Process body content. 145
BodyTag
• It extends IterationTag and defines
additional methods that let a tag handler
to manipulate body content by providing
buffering.
void doInitBody()
Action method to handle body evaluation.
Invoked after setBodyContent().
153
Class TagSupport
• Is a utility class to be extended by new tag
handlers instead of implementing
Tag/IterationTag.
• 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
• 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
instance.
• 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)
161
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 java.io.Reader getReader()
Return value of this BodyContent as a Reader.
• abstract String getString()
Return value of the BodyContent as a String.
• abstract void writeOut(java.io.Writer out)
Write contents of this BodyContent into a
Writer.
163
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
variables
– to perform translation-time validation of
the tag attributes.
164
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
instance.
• boolean isValid(TagData data)
Translation-time validation of the attributes.
• void setTagInfo(TagInfo tagInfo)
Set the TagInfo for this class.
165
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.
166
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
BODY_CONTENT_TAG_DEPENDENT
static constant for getBodyContent() when it
is Tag dependent
167
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()
169
Class VariableInfo
• Provides information about scripting
variables.
• This information is provided by
TagExtraInfo classes and it is used during
translation of JSP.
170
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()
171
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
JSP1.2
172
Method Summary
• String getNameGiven()
• String getNameFromAttribute()
• String getClassName()
• boolean getDeclare()
• int getScope()
173
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.
174
Method Summary
• String getName()
• boolean isRequired()
• boolean canBeRequestTime()
• String getTypeName()
175
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.
176
Field Summary
• protected String tlibversion
• protected String jspversion
• protected String shortname
• protected String uri
• protected String info
177
Method Summary
• String getRequiredVersion()
• String getShortName()
• String getURI()
• String getInfoString()
178
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
file.
Field Summary
static String ID "id" is wired in to be ID.
Constructor Summary
TagAttributeInfo( String name, boolean
required, String type, boolean reqTime)
180
Method Summary
boolean canBeRequestTime()
Determines whether this attribute can hold a request-time
value.
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.
181
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.
183
Simple tags
• Handler for simple tag must implement
doStartTag and doEndTag methods of Tag
interface.
• 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:
190
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.