Professional Documents
Culture Documents
1
Understanding
•Java Server Pages isJSP
another technology
defined by Sun Microsystems to generate
dynamic web content.
•JSP is a form of server-side applications.
•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 .jsp2
Understanding
JSP which are
They are HTML documents
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.*;
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 functionality
architecture
17
jspInit()
JSP life cycle
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
18
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
destroy() method and is called just before the
generated servlet is destroyed. 19
Package
Interface Hierarchy
java.servlet.jsp
Class Hierarchy
20
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()
23
Class JspFactory
Defines factory methods available to a JSP
page at runtime to enable instantiation of
implementation-dependent PageContext and
JspEngineInfo that support JSP
implementation.
JSP Engine, during it's startup instantiates an
( Exception e)
Redirects exception to the specified error page
(if available) or to default handler.
abstract void handlePageException
( Throwable t ) 32
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.
BodyContent pushBody()
Returns a new BodyContent object, and updates
the value of "out“ attribute in the page scope
attribute namespace of the PageContext. 34
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() 35
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)
36
Tag convention
JSP tags usage is similar to those of
HTML tags:
They begin and end with angle
brackets.
ASP.
Tags based on XML style.
37
ASP-like Tags
They can be recognized by their delimiters.
They start with <% and end with %>.
40
Example
1. <jsp:forward page="admin.jsp"/>
2. <jsp:useBean id="login“
class="UserBean">
<jsp:setProperty name="login“
property="group“
value="admin"/>
</jsp:useBean>
41
Components of a JSP
program
• HTML code
• Comments
• JSP tags
• JSP Implicit Objects
• Java Beans
42
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” );
}
%> 43
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 %>
44
JSP
•Directives tag types…
• 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> 45
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>
47
Deploying JSP’s on
TOMCAT
48
Deploying JSP’s on J2EE RI
Server
49
Deploying JSP’s on
Weblogic
50
Deploying JSP’s on JRun
51
Sample Program - 2
•Hello word example
<%
String name = null;
name = request.getParameter(“name”);
if ( name == null ) {
%>
Hello, World
<% } else
{
out.println(“Hello ” + name);
}
%> 52
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>
53
Sample Program - 4
•Simple usage of page directive, scriptlet 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>
57
Control statements in JSP
Sample
•Using for loops
Program - 7
<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>
58
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>
59
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.
60
JSP Objects description
JSP object Servlet API Object Description
application javax.servlet.ServletContext Context (Execution
environment) of the
Servlet.
61
JSP Objects description…
JSP object Servlet API Object Description
pageContext javax.servlet.jsp.PageContext Page context
for the JSP.
request javax.servlet.HttpServletRequest The client
request.
response javax.servlet.HttpServletResponse The response
to the client.
session javax.servlet.http.HttpSession Session object
created for
requesting
client.
68
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>
69
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>
70
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) 71
Sample Program - 12
<HTML> <BODY>
<h2>Display the default application settings</h2>
<%
out.println( application.getServerInfo() + "<br><br>" );
72
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.
73
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>
74
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()
75
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(...)
76
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)
77
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>
78
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.79
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.
80
Handling of Actions
JSP translators treat action tags as
library.
The translator simply replaces action
82
Action tags
Following action tags are available:
<jsp:useBean>
<jsp:getProperty>
<jsp:setProperty>
<jsp:param>
<jsp:forward>
<jsp:include>
<jsp:plugin>
83
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 />
84
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.
beanName Bean name as per bean spec.
type Reference type (super class or
same type).
85
Attributes in useBean
tag
Possible combination of attributes in
Possible combination of attributes in
useBean tag:
Attributes:
name
property
param
value
87
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,
•Syntax:
<jsp:getProperty attr_name=attri_val />
Attributes:
name->bean id specified in useBean.
property-> property whose value is to
retrieved.
90
Bean access code 1
package test;
(bean)
public class StudentBean
{ test/StudentBean.java
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; }
}
91
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>
92
Beans and Form
processing
package test2;
96
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)
97
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.
98
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>
99
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
/>
100
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.
101
Sample Code
<HTML>
<HEAD><TITLE>Example Of The forward Action</TITLE></HEAD>
<BODY>
102
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>
103
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
/> 104
Directives
Directives give instructions to the JSP
container to be interpreted at translation
time.
The general Syntax:
<%@ directivename attribute=“value”
attribute=”value”%>
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
<html> <body>
<!--
<%= "hello" %>
<%@page info="haal chaal kya khabar" %>
-->
<%= getServletInfo() %>
</body> </html>
108
Handling Exceptions using
<html> <body>
errorPage
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>
109
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" %>
110
<html>
Sample Code
<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>
111
include directive vs include
action
directive action
Included at JSP Included at JSP
translation time. request time.
Inclusion is static in Inclusion is
nature. dynamic.
Recommended for Web component
static/template usage recommended.
data.
Cannot pass Can pass parameters
parameters. using <param> 112
Tag libraries
<taglib> directive
113
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
114
Tag Library
It is a collection of custom actions/tags,
(portable elements) 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. 115
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. 116
taglib Directive
•It allows us to access user-defined/custom
tags in a JSP.
•Syntax:
<%@ taglib
uri=“tld uri”
prefix=“unique name”
%>
Direct reference
<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> 128
Code – Java class
package test;
import java.util.Date;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
130
Custom
Tag types
131
Simple Tags
A simple tag contains no body and no
attributes.
Ex: <prefix_name:tag_name />
135
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" />
140
Tag
It defines a handler for simple tags
Method Summary
int doAfterBody()
void doInitBody()
Action method to handle body evaluation.
Invoked after setBodyContent().
155
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. 156
Field
protected String
Summary
id
protected PageContext pageContext
EVAL_PAGE
SKIP_BODY
SKIP_PAGE
String getId()
The value of the id attribute of this tag; or null.
void setId(String id)
Object getValue(String k)
Get a the value associated with a key.
Enumeration getValues()
void removeValue(String k)
pageContext
EVAL_PAGE
SKIP_BODY, SKIP_PAGE
EVAL_BODY_TAG (Deprecated)
161
Method
int doStartTag()
Summary
Default processing of start tag.
void setBodyContent(BodyContent b)
163
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(). 164
Method Summary
protected BodyContent(JspWriter e)
void clearBody()
abstract java.io.Reader getReader()
168
Field Summary
static String BODY_CONTENT_EMPTY
static constant for getBodyContent() when it
is empty
static String BODY_CONTENT_JSP
BODY_CONTENT_TAG_DEPENDENT
static constant for getBodyContent() when it
is Tag dependent
169
Method
String getTagName()
Summary
String getTagClassName()
TagExtraInfo getTagExtraInfo()
The instance (if any) for extra tag information
String getBodyContent()
String getDisplayName()
String getSmallIcon()
String getLargeIcon()
String getInfoString() 170
Method Summary…
TagAttributeInfo[] getAttributes()
TagVariableInfo[] getTagVariableInfos()
TagLibraryInfo getTagLibrary()
171
Class VariableInfo
Provides information about scripting
variables.
This information is provided by
TagExtraInfo classes and it is used during
translation of JSP.
172
Member
Field Summary
summary
static int AT_BEGIN
static int AT_END
static int NESTED
Method Summary
String getVarName()
String getClassName()
boolean getDeclare()
int getScope()
173
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
174
Method Summary
String getNameGiven()
String getNameFromAttribute()
String getClassName()
boolean getDeclare()
int getScope()
175
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.
176
Method Summary
String getName()
boolean isRequired()
boolean canBeRequestTime()
String getTypeName()
177
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.
178
Field Summary
protected String tlibversion
protected String jspversion
protected String shortname
protected String uri
protected String info
179
Method Summary
String getRequiredVersion()
String getShortName()
String getURI()
String getInfoString()
180
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. 181
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)
182
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.
183
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.
185
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. 186
Simple tag - Example
A simple tag <tt:simple /> would be implemented by the
following tag handler:
<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; } 188
Attribute Validation
The tag library documentation should describe
valid values for tag attributes.
192
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
199
The table below summarizes object scopes.
Name Accessible From Lifetime
Until response has been
sent back to user or
page Current page
request is passed to a new
page
Current and any included Until the response has
request
or forwarded pages been sent back to the user
Current request and any
subsequent request from
session Life of user's session
same browser (subject to
session lifetime)
Current and any future
application request from the same Life of the application
Web application
200
Providing Information about
Scripting Variable
The example below defines a scripting
variable book that is used for accessing book
information:
<bean:define id="book" name="bookDB"
property="bookDetails“
type="database.BookDetails"/>
<font color="red" size="+2">
<%=messages.getString("CartRemoved")%>
<strong><jsp:getProperty name="book“
property="title"/></strong>
<br> <br>
</font>
201
When the JSP page containing this tag is translated,
the Web container generates code to synchronize the
scripting variable with the object referenced by the
variable. To generate the code, the Web container
requires certain information about the scripting
variable:
Variable name
Variable class
Whether the variable refers to a new or existing
object
The availability of the variable.