Upload
mohanraop
View
14
Download
3
Tags:
Embed Size (px)
Citation preview
11
Programming
22
Understanding Understanding JSPJSP•Java Server Pages is 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 .jsp
33
Understanding Understanding JSPJSPThey are HTML documents which are They are HTML documents which are
embedded with Java code using different embedded with Java code using different
JSP tags.JSP tags.When compared with servlets they are When compared with servlets they are
unstructured and contains pieces of java unstructured and contains pieces of java
code scattered through out an HTML file.code scattered through out an HTML file.Since they are server-side applications, Since they are server-side applications,
they have access to server resources such they have access to server resources such
as servlets, javabeans, Ejbs and as servlets, javabeans, Ejbs and
databases.databases.
44
Advantages of Advantages of JSPJSP•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.
55
Advantages of Advantages of JSPJSP JSP being vendor-neutral, developers and JSP being vendor-neutral, developers and
system architects can select best-of-system architects can select best-of-
breed solutions at all stages of JSP breed solutions at all stages of JSP
deployment.deployment.
It has full access to the underlying J2SE It has full access to the underlying J2SE
APIs (database access, directory services, APIs (database access, directory services,
distributed computing, cryptography…).distributed computing, cryptography…).
Hence JSP is highly flexible and feature-Hence JSP is highly flexible and feature-
rich to create web-based applications.rich to create web-based applications.
66
Advantages of Advantages of JSPJSP Does not require server restart when Does not require server restart when
the JSP program code changes.the JSP program code changes.
Separation of roles into graphical Separation of roles into graphical
content and dynamic content.content and dynamic content.
JSP’s being a modified way of writing JSP’s being a modified way of writing
servlets, they can provide all servlets, they can provide all
features/capabilities of a servlets.features/capabilities of a servlets.
77
JSP HistoryJSP History Servlets first appeared as part of Servlets first appeared as part of
Sun’s Java Web Server (JWS), a Java Sun’s Java Web Server (JWS), a Java
based HTTP server in 1997.based HTTP server in 1997.
Sun eventually released the Servlet Sun eventually released the Servlet
technology as a standard Java technology as a standard Java
extension. extension.
JSP soon followed, with the first draft JSP soon followed, with the first draft
API specifications appearing in API specifications appearing in 1998.1998.
88
JSP HistoryJSP History JSP 1.0 Specification was JSP 1.0 Specification was
released in June 1999 as a released in June 1999 as a
part of J2EE.part of J2EE.
JSP 1.1 - Late 1999.JSP 1.1 - Late 1999.
JSP 1.2 - 2001.JSP 1.2 - 2001.
JSP 2.0 – 2003.JSP 2.0 – 2003.
99
Third party vendor Third party vendor supportsupportRAD tools are now available to create RAD tools are now available to create
dynamic web pages, using DnD approach. dynamic web pages, using DnD approach. Ability to create sophisticated JSP pages Ability to create sophisticated JSP pages
without seeing HTML tags, let alone Java without seeing HTML tags, let alone Java
code will enhance the productivity to a code will enhance the productivity to a
greater extent.greater extent.Ex:Ex: Drumbeat 2000 from MacromediaDrumbeat 2000 from Macromedia
IBM’s Visual Age for JavaIBM’s Visual Age for Java
HomeSite from AllaireHomeSite from Allaire
1010
JSP vs ASPJSP vs ASPFeatures Features AspAsp JspJsp
WEB ServerWEB Server IIS, PWSIIS, PWS ManyMany
Platform Platform WindowWindows s
AnyAny
Reusable Reusable components components
ComCom Javabeans/EJBJavabeans/EJB
Memory leak Memory leak protection protection
NoNo YesYes
Scripting languages Scripting languages J-script,J-script,VB-VB-scriptscript
JavaJava
Security Security NoNo yesyes
Customized tags Customized tags NoNo yesyes
1111
JSP vs JSP vs JavaScriptJavaScript JavaScriptJavaScript
Validates on Client SideValidates on Client Side
Browser DependentBrowser Dependent
UnstableUnstable
InterpretedInterpreted
Server-side JavaScript is Server-side JavaScript is
dependent on proprietary servers.dependent on proprietary servers.
1212
JSP vs ServletsJSP vs Servlets SimilaritiesSimilarities
Provides identical results to Provides identical results to
end user.end user.
JSP is an extension of servlets.JSP is an extension of servlets.
Provides similar API support.Provides similar API support.
1313
JSP vs ServletsJSP vs Servlets DifferencesDifferences Servlets: Servlets: “HTML embedded in Java Code”“HTML embedded in Java Code”
HTML code inaccessible to Graphics designerHTML code inaccessible to Graphics designer
But accessible to Programmer.But accessible to Programmer.
JSP: JSP: “Java Code embedded in HTML”“Java Code embedded in HTML”
HTML code accessible to Graphic DesignerHTML code accessible to Graphic Designer
Java code accessible to Programmer.Java code accessible to Programmer.
Jsp allows code update without Jsp allows code update without
restarting the server.restarting the server. Eliminates redundant code.Eliminates redundant code.
1414
Comparing servlet and JSP Comparing servlet and JSP codecode
1. import java.io.*;2. import javax.servlet.*;3. import javax.servlet.http.*;
4. public class HelloWorld extends HttpServlet 5. {6. public void doGet(HttpServletRequest req, HttpServletResponse res)7. throws ServletException, IOException 8. {9. res.setContentType("text/html");10. PrintWriter out = res.getWriter();11. out.println("<HTML>");12. out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");13. out.println("<BODY>");14. out.println("<BIG>Hello World</BIG>");15. out.println("</BODY></HTML>");16. }17.}
1515
Comparing servlet and JSP Comparing servlet and JSP codecode
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.
1616
JSP functionality JSP functionality architecturearchitecture
Web Client
Web Server
JSP Page
Generated Servlet
Compiled Servlet
Request
Response
Translation by JSP engine
Servlet is loaded to server
Compilation
Instantiation
1717
JSP functionality JSP functionality architecturearchitecture
1818
JSP life cycleJSP life cycle jspInit()jspInit() jspDestroy()jspDestroy() _jspService( request, response )_jspService( request, response )
jspInit()Initialise JSP
Invoked only once
_jspService(request,response)Handle Requests:
invoked for every request
jspDestroy()Invoked by containerto cleanup
•Implementation of these methods are generated by the Container and not by JSP authors.
1919
JSP and the JSP EngineJSP and the JSP Engine Contract between the JSP engine and JSPContract between the JSP engine and JSP
jspInit()jspInit() Corresponds to servlet init(), but has Corresponds to servlet init(), but has no parameters (use config implicit object to no parameters (use config implicit object to obtain information regarding environment).obtain information regarding environment).
jspService()jspService() The main processing method; all The main processing method; all Java code belongs to this method by default Java code belongs to this method by default (if not contained in another method), but (if not contained in another method), but it is it is not explicitly declared in a JSP documentnot explicitly declared in a JSP document..
jspDestroy()jspDestroy() Corresponds to the servlet Corresponds to the servlet destroy() method and is called just before the destroy() method and is called just before the generated servlet is destroyed.generated servlet is destroyed.
2020
Package java.servlet.jspPackage java.servlet.jsp
Class Hierarchy
Interface Hierarchy
2121
Interface Interface javax.servlet.Servletjavax.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()
•public ServletConfig getServletConfig()•public String getServletInfo()
2222
Interface JspPageInterface JspPage It describes the generic interaction that a JSP It describes the generic interaction that a JSP Page implementation class must satisfy.Page implementation class must satisfy.
Pages that use HTTP protocol are described Pages that use HTTP protocol are described by HttpJspPage interface.by HttpJspPage interface.
public void jspInit() public void jspInit() Invoked when the JSP page is Invoked when the JSP page is
initialized. initialized. public void jspDestroy() public void jspDestroy()
Invoked before destroying the JSP page.Invoked before destroying the JSP page.
Note:Note: The jspInit() and jspDestroy() can be The jspInit() and jspDestroy() can be defined by a JSP author, but _jspService() is defined by a JSP author, but _jspService() is defined automatically by the JSP processor defined automatically by the JSP processor based on contents of the JSP page. based on contents of the JSP page.
2323
Interface Interface HttpJspPageHttpJspPage Extends JspPage and describes interaction Extends JspPage and describes interaction
that a JSP Page implementation class must that a JSP Page implementation class must satisfy when using HTTP protocol. satisfy when using HTTP protocol.
Behaviour is identical to JspPage, except Behaviour is identical to JspPage, except that _jspService method is now expressible that _jspService method is now expressible in Java type system optimized for HTTP. in Java type system optimized for HTTP.
void _jspService( HttpServletRequest void _jspService( HttpServletRequest request, HttpServletResponse response) request, HttpServletResponse response)
It corresponds to body of the JSP page.It corresponds to body of the JSP page. It is defined automatically by the JSP container.It is defined automatically by the JSP container.
2424
Class JspFactoryClass JspFactoryDefines factory methods available to a JSP Defines factory methods available to a JSP page at runtime to enable instantiation of page at runtime to enable instantiation of implementation-dependent PageContext and implementation-dependent PageContext and JspEngineInfo that support JSP implementation.JspEngineInfo that support JSP implementation.JSP Engine, during it's startup instantiates an JSP Engine, during it's startup instantiates an implementation dependent subclass of this implementation dependent subclass of this class.class.This instance is made globally available by This instance is made globally available by registering it using setDefaultFactory() registering it using setDefaultFactory() method. method.
Note: JspFactory objects should not be used by Note: JspFactory objects should not be used by JSP page authorsJSP page authors..
2525
Class JspFactoryClass JspFactory static static void void setDefaultFactory(JspFactory deflt) setDefaultFactory(JspFactory deflt) static static JspFactory JspFactory getDefaultFactory() getDefaultFactory() abstract JspEngineInfo abstract JspEngineInfo getEngineInfo() getEngineInfo() abstract PageContext abstract PageContext getPageContext(getPageContext(
Servlet servlet,Servlet servlet,ServletRequest request, ServletRequest request, ServletResponse response, ServletResponse response, String errorPageURL, String errorPageURL, boolean needsSession, boolean needsSession, int buffer, int buffer, boolean autoflush) boolean autoflush)
Instantiates an implementation dependent Instantiates an implementation dependent PageContext for the calling Servlet. PageContext for the calling Servlet.
abstract void abstract void releasePageContext(PageContext pc) releasePageContext(PageContext pc)
2626
Class JspEngineInfoClass JspEngineInfo Provides information about the Provides information about the
current JSP engine (container).current JSP engine (container).
abstract String abstract String getSpecificationVersion() getSpecificationVersion()
Return version of the JSP Return version of the JSP specification supported by this JSP specification supported by this JSP engine.engine.
May return null, if version details May return null, if version details is not known.is not known.
2727
Class PageContextClass PageContext Provides access to JSP implicit Provides access to JSP implicit
objects and page attributes.objects and page attributes.
It is an abstract class, and is It is an abstract class, and is
implemented by container provider.implemented by container provider.
It is instantiated using static method It is instantiated using static method
getPageContext() and is released getPageContext() and is released
using releasePageContext() of using releasePageContext() of
JspFactory. JspFactory.
2828
FieldField SummarySummary static String static String APPLICATION APPLICATION Name used to store ServletContext in Name used to store ServletContext in
PageContext name table. PageContext name table. static String static String CONFIG CONFIG Name used to store ServletConfig.Name used to store ServletConfig. static String static String EXCEPTION EXCEPTION Name used for uncaught exception.Name used for uncaught exception. static String static String OUT OUT Name used to store current JspWriter.Name used to store current JspWriter. static Stringstatic String PAGE PAGE Name used to store the Servlet.Name used to store the Servlet. static String static String PAGECONTEXT PAGECONTEXT Name used to store this PageContext.Name used to store this PageContext.
2929
FieldField Summary…Summary… static String static String REQUEST REQUEST Name used to store ServletRequest.Name used to store ServletRequest. static String static String RESPONSE RESPONSE Name used to store ServletResponse.Name used to store ServletResponse. static String static String SESSION SESSION Name used to store HttpSession.Name used to store HttpSession.
static int PAGE_SCOPE static int PAGE_SCOPE static int REQUEST_SCOPE static int REQUEST_SCOPE static int SESSION_SCOPEstatic int SESSION_SCOPE static int APPLICATION_SCOPEstatic int APPLICATION_SCOPE
Indicates scope of a bean reference.
3030
Method SummaryMethod Summary The following methods provide convenient The following methods provide convenient access to implicit objects:access to implicit objects:
abstract JspWriter abstract JspWriter getOut()getOut() Returns current value of the out object Returns current value of the out object (JspWriter). (JspWriter).
abstract Object abstract Object getPage() getPage() abstract ServletRequest abstract ServletRequest getRequest()getRequest() abstract ServletResponse abstract ServletResponse getResponse()getResponse() abstract ServletConfig abstract ServletConfig
getServletConfig()getServletConfig() abstract ServletContext getServletContext()abstract ServletContext getServletContext() abstract HttpSession abstract HttpSession getSession() getSession() abstract Exception abstract Exception getException() getException()
3131
Method SummaryMethod Summary Object findAttribute( String name) Object findAttribute( String name) Search and return attribute value (or null) in scope Search and return attribute value (or null) in scope
sequence of page, request, session and application.sequence of page, request, session and application. Object getAttribute( String name) Object getAttribute( String name) Return attribute value of name in page scope.Return attribute value of name in page scope. Enumeration getAttributeNamesInScope(int scope)Enumeration getAttributeNamesInScope(int scope) abstract int getAttributesScope( String name)abstract int getAttributesScope( String name) void removeAttribute( String name)void removeAttribute( String name) Search for attribute in scope order and remove it.Search for attribute in scope order and remove it. void removeAttribute( String name, int scope)void removeAttribute( String name, int scope) void setAttribute( String name, Object value)void setAttribute( String name, Object value) Register attribute in page scope. Register attribute in page scope. void setAttribute( String name, Object v, int scope)void setAttribute( String name, Object v, int scope)
3232
Method SummaryMethod Summary abstract void forward( String relativeUrlPath)abstract void forward( String relativeUrlPath)
Re-directs/forwards current Request andRe-directs/forwards current Request and
Response to another component. Response to another component. abstract void include( String relativeUrlPath)abstract void include( String relativeUrlPath)
Inserts content/output of refered component.Inserts content/output of refered component. abstract void handlePageExceptionabstract void handlePageException ( Exception e)( Exception e)
Redirects exception to the specified error pageRedirects exception to the specified error page
(if available) or to default handler.(if available) or to default handler. abstract void handlePageExceptionabstract void handlePageException
( Throwable t )( Throwable t )
3333
Method SummaryMethod Summary abstract void initialize(Servlet ser, abstract void initialize(Servlet ser, ServletRequest req, ServletResponse res, ServletRequest req, ServletResponse res, String errorPageURL, boolean needsSession, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush)int bufferSize, boolean autoFlush)
Initializes PageContext to be used by a JSP toInitializes PageContext to be used by a JSP to
service an incoming request. service an incoming request.
abstract void release()abstract void release()
It resets PageContext state, releasing internalIt resets PageContext state, releasing internal
references and preparing PageContext forreferences and preparing PageContext for
reuse by a later invocation of initialize(). reuse by a later invocation of initialize().
3434
Method SummaryMethod SummaryFollowing methods enable management of Following methods enable management of
JspWriter streams to implement Tag JspWriter streams to implement Tag Extensions:Extensions:
JspWriter popBody()JspWriter popBody()
Returns JspWriter saved by the matching Returns JspWriter saved by the matching pushBody(), and updates value of "out“ pushBody(), and updates value of "out“ attribute in page scope of the PageConxtext.attribute in page scope of the PageConxtext.
BodyContent pushBody()BodyContent pushBody()
Returns a new BodyContent object, and updates Returns a new BodyContent object, and updates the value of "out“ attribute in the page scope the value of "out“ attribute in the page scope attribute namespace of the PageContext.attribute namespace of the PageContext.
3535
Class JspWriterClass JspWriter Provides output stream for JSP's.Provides output stream for JSP's. It extends java.io.Writer.It extends java.io.Writer. A JSPWriter object is available within A JSPWriter object is available within
JSP as implicit object JSP as implicit object outout, which is , which is initialized automatically using methods initialized automatically using methods of PageContext object.of PageContext object.
abstract abstract void void clearBuffer() clearBuffer() abstract abstract void void close() close() abstract abstract void void flush() flush() int int getBufferSize() getBufferSize() abstract abstract int int getRemaining() getRemaining() boolean boolean isAutoFlush() isAutoFlush() abstract abstract void void newLine() newLine()
3636
Class JspWriter…Class JspWriter…void print(boolean b) void print(boolean b)
void print(char c) void print(char c)
void print(char[] s) void print(char[] s)
void print(double d) void print(double d)
void print(float f) void print(float f)
void print(int i) void print(int i)
void print(long l) void print(long l)
void print(Object obj) void print(Object obj)
void print(String s)void print(String s)
void println() void println(boolean x) void println(char x) void println(char[] x) void println(double x) void println(float x) void println(int x) void println(long x) void println(Object x) void println(String x)
3737
Tag conventionTag convention JSP tags usage is similar to those of JSP tags usage is similar to those of HTML tags:HTML tags: They begin and end with angle They begin and end with angle
brackets.brackets.
JSP tags fall into 2 basic categories: JSP tags fall into 2 basic categories: Scripting-oriented tags inspired by Scripting-oriented tags inspired by
ASP.ASP. Tags based on XML style.Tags based on XML style.
3838
ASP-like TagsASP-like Tags They can be recognized by their delimiters.They can be recognized by their delimiters. They start with <% and end with %>. They start with <% and end with %>. Additional character may appear after the Additional character may appear after the
initial <%, such as !, =, or @, to further initial <%, such as !, =, or @, to further specify the meaning of the tag. specify the meaning of the tag.
Example:Example:<%! double radius = 7.5; %><%! double radius = 7.5; %><%= 2 * Math.PI * radius %><%= 2 * Math.PI * radius %><% if (radius > 10.0) <% if (radius > 10.0)
{{out.println("Exceeds recommended out.println("Exceeds recommended
maximum");maximum"); } %>} %><%@ include file="copyright.html" %><%@ include file="copyright.html" %>
3939
ASP-like Tags…ASP-like Tags… NOTE :NOTE :
All ASP-scripting like tags are All ASP-scripting like tags are self-contained.self-contained.
All the information relevant to All the information relevant to the tag, and all of the data it the tag, and all of the data it will act on, is contained within will act on, is contained within the individual tags themselves.the individual tags themselves.
None of these scripting-oriented None of these scripting-oriented JSP tags have bodies.JSP tags have bodies.
4040
XML-like tagsXML-like tags They start with < and not <%They start with < and not <% Tag names have an embedded colon.Tag names have an embedded colon. They are similar to HTML tags; They can have They are similar to HTML tags; They can have
a "start tag", a "tag body" and an "end tag".a "start tag", a "tag body" and an "end tag". XML syntax is similar to HTML, but adds a few XML syntax is similar to HTML, but adds a few
rules to avoid certain problems.rules to avoid certain problems. XML tags are case sensitive (<title> and XML tags are case sensitive (<title> and
<TITLE> are treated as two different tags).<TITLE> are treated as two different tags). All attribute values must be quoted (In All attribute values must be quoted (In
HTML, quotes are optional).HTML, quotes are optional). All XML tags must also have a delimiting All XML tags must also have a delimiting
tag.tag.
4141
ExampleExample1. 1. <jsp:forward page="admin.jsp"/><jsp:forward page="admin.jsp"/>
2. 2. <jsp:useBean id="login“ <jsp:useBean id="login“ class="UserBean">class="UserBean">
<jsp:setProperty <jsp:setProperty name="login“ name="login“ property="group“ property="group“ value="admin"/>value="admin"/>
</jsp:useBean></jsp:useBean>
4242
Components of a JSP Components of a JSP programprogram
• HTML code
• JSP tags
• JSP Implicit Objects
• Java Beans
• Comments
4343
Comments in JSPComments in JSP1. Plain HTML Comments
Ex: <!-- hello --> Response: <!-- hello -->
2. HTML Comments containing JSP tagsEx: < !-- value of 10 + 20 is <%= 10 + 20 %> --> Response: <!-- value of 10 + 20 is 30 -->
3. JSP Comment tagEx: <%-- This is a JSP comment --%>Response:
4. Java CommentsEx: <% /* int x;
float f; */void meth1(){
//out.println( “hello output” );}
%>
4444
JSP tag typesJSP 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 %>
4545
JSP tag types…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>
4646
General rulesGeneral rules JSP tags are case sensitiveJSP tags are case sensitive
Tags may have attributesTags may have attributes
Attribute values must always appear Attribute values must always appear quotedquoted
White space with in the JSP page is not White space with in the JSP page is not significantsignificant
The \ character can be used as an The \ character can be used as an escape sequenceescape sequence
4747
Sample Program -1Sample Program -1
<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>
•Using simple expression tag
4848
Deploying JSP’s on Deploying JSP’s on TOMCATTOMCAT
4949
Deploying JSP’s on J2EE RI Deploying JSP’s on J2EE RI ServerServer
5050
Deploying JSP’s on Deploying JSP’s on WeblogicWeblogic
5151
Deploying JSP’s on JRunDeploying JSP’s on JRun
5252
Sample Program - 2Sample Program - 2<% <%
String name = null;String name = null; name = name =
request.getParameter(“name”);request.getParameter(“name”); if ( name == null ) { if ( name == null ) { %>%> Hello, WorldHello, World<% } else <% } else
{{ out.println(“Hello ” + name);out.println(“Hello ” + name);
} } %>%>
•Hello word example
5353
Sample Program - 3Sample Program - 3<html> <body><html> <body>Java Version : <%= Java Version : <%=
System.getProperty( "java.version" ) %> <br>System.getProperty( "java.version" ) %> <br>Java Home : <%= Java Home : <%=
System.getProperty( "java.home" ) %> <br>System.getProperty( "java.home" ) %> <br>Os Name : <%= System.getProperty( "os.name" ) Os Name : <%= System.getProperty( "os.name" )
%> %> <br><br>
User Name : <%= User Name : <%= System.getProperty( "user.name" ) %> <br>System.getProperty( "user.name" ) %> <br>
User Home : <%= System.getProperty( "user.home" User Home : <%= System.getProperty( "user.home" ) %> <br>) %> <br>
User Directory : <%= User Directory : <%= System.getProperty( "user.dir" ) %> <br>System.getProperty( "user.dir" ) %> <br>
</body> </html></body> </html>
5454
<%@ page import="java.util.*" %><HTML> <BODY> <% System.out.println( "Evaluating date now" ); Date date = new Date(); %> Hello! The time is now <%= date %> </BODY></HTML>
Sample Program - 4Sample Program - 4•Simple usage of page directive, scriptlet and expression tags.
5555
<%@ page import="java.util.*" %><HTML> <BODY> <%! Date dateobj = new Date(); Date getDate() {
System.out.println( "In getDate() method" );
return dateobj; } %> Hello! The time is now <%= getDate() %></BODY> </HTML>
Sample Program - 5Sample Program - 5 •Using page directive, declaration tag and expression tags together.
5656
Note about declaration Note about declaration tagstags
Declarations in Declaration tag will become Declarations in Declaration tag will become instance members.instance members.
Variables in Declaration tags will be Variables in Declaration tags will be evaluated only once, during translation of evaluated only once, during translation of the JSP page. the JSP page.
Its behavior is same as definition of Its behavior is same as definition of instance variables in a class.instance variables in a class.
Hence it will not have different Hence it will not have different functionality for different clients.functionality for different clients.
Client specific data must not be put in Client specific data must not be put in declaration tags, since they are shared. declaration tags, since they are shared. Sessions can be used for the purpose.Sessions can be used for the purpose.
5757
Control statements in JSPControl statements in JSP•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>
Sample Program - 6Sample Program - 6
5858
Control statements in JSPControl statements in JSP•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>
Sample Program - 7 Sample Program - 7
5959
Control statements in JSPControl statements in JSP
<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];%>
<h<%= i %> ><font color=<%=col%> > Welcome to Step India </font>
</h<%= i %> >
<% } %></center></body> </html>
•Another example of using for loopsSample Program - 8 Sample Program - 8
6060
Built-in/Implicit JSP Built-in/Implicit JSP ObjectsObjects•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.
6161
JSP Objects descriptionJSP Objects descriptionJSP JSP
objectobjectServlet API Object Servlet API Object DescriptionDescription
applicatioapplicationn
javax.servlet.ServletContjavax.servlet.ServletContext ext
Context (Execution Context (Execution environment) of environment) of the Servlet.the Servlet.
config config javax.servlet.ServletConfijavax.servlet.ServletConfig g
The ServletConfig The ServletConfig for the JSP.for the JSP.
exception exception java.lang.Throwable java.lang.Throwable The exception that The exception that resulted when an resulted when an error occurred.error occurred.
out out javax.servlet.jsp.JspWritejavax.servlet.jsp.JspWriter r
An object that An object that writes into a JSP's writes into a JSP's output stream.output stream.
6262
JSP Objects description…JSP Objects description…JSP objectJSP object Servlet API Object Servlet API Object DescriptionDescription
pageContepageContextxt
javax.servlet.jsp.PageContext javax.servlet.jsp.PageContext Page context Page context for the JSP.for the JSP.
request request javax.servlet.HttpServletRequjavax.servlet.HttpServletRequest est
The client The client request.request.
response response javax.servlet.HttpServletRespojavax.servlet.HttpServletResponsense
The response The response to the client.to the client.
session session javax.servlet.http.HttpSessiojavax.servlet.http.HttpSession n
Session Session object object created for created for requesting requesting client.client.
pagepage javax.servlet.Servletjavax.servlet.Servlet Refers to Refers to current current servlet object.servlet object.
6363
•It provides access to data sent within a HTTP Request. request objectrequest object
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()
6464
Sample Program - 9Sample Program - 9 <%@ page language="java" contentType="text/html" %>
<html> <body bgcolor="white" > The following information was received :
<ul>
<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") %>
</ul></body> </html>
6565
•It allows setting of response message including html Code, cookies, headers and other information.
response response objectobject
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)
6666
Sample Program - 10 Sample Program - 10 <html> <body>
<% Cookie cookies[] = request.getCookies();boolean flag = false;String name;try{
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" ) );
}%></body></hml>
6767
session objectsession object•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)
6868
session object (Contd)session object (Contd)
String String getId() getId()
long long getCreationTime() getCreationTime()
long long getLastAccessedTime() getLastAccessedTime()
int int getMaxInactiveInterval() getMaxInactiveInterval()
void void setMaxInactiveInterval(int setMaxInactiveInterval(int interval) interval)
ServletContext ServletContext getServletContext() getServletContext()
HttpSessionContext HttpSessionContext getSessionContext() getSessionContext()
void void invalidate() invalidate()
boolean boolean isNew() isNew()
6969
Sample Program - 11Sample 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>
7070
Sample Program - 12Sample Program - 12<HTML> <BODY><HTML> <BODY>
<FORM METHOD=POST ACTION="http://localhost:8080/aaa/B.jsp"><FORM METHOD=POST ACTION="http://localhost:8080/aaa/B.jsp">What's your name? <INPUT TYPE=TEXT NAME=username What's your name? <INPUT TYPE=TEXT NAME=username
SIZE=20>SIZE=20><P><INPUT TYPE=SUBMIT><P><INPUT TYPE=SUBMIT>
</FORM></FORM></BODY> </HTML> </BODY> </HTML>
<% <% String name = request.getParameter( "username" );String name = request.getParameter( "username" );
session.setAttribute( "theName", name );session.setAttribute( "theName", name );%>%><HTML><HTML> <BODY><BODY>
<A HREF="http://localhost:8080/aaa/C.jsp">Continue</A><A HREF="http://localhost:8080/aaa/C.jsp">Continue</A></BODY></HTML></BODY></HTML>
<HTML><BODY><HTML><BODY>Hello, <%= session.getAttribute( "theName" ) %>Hello, <%= session.getAttribute( "theName" ) %>
</BODY></HTML></BODY></HTML>
B.jsp
A.jsp
C.jsp
7171
application objectapplication 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)
7272
Sample Program - 12Sample Program - 12<HTML> <BODY>
<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>");
} %>
</BODY> </HTML>
7373
config objectconfig objectIt 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()
7474
Sample Program - 13Sample 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>
7575
exception objectexception 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()
7676
out objectout objectIt 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(...)
7777
pagecontext objectpagecontext 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)
7878
Sample CodeSample Code<html><body><html><body>
<%<%Object val = pageContext.findAttribute( pageContext.PAGE );Object val = pageContext.findAttribute( pageContext.PAGE );out.println( val + "<br>" );out.println( val + "<br>" );val = pageContext.findAttribute( pageContext.APPLICATION );val = pageContext.findAttribute( pageContext.APPLICATION );out.println( val + "<br>" );out.println( val + "<br>" );val = pageContext.findAttribute( pageContext.CONFIG );val = pageContext.findAttribute( pageContext.CONFIG );out.println( val + "<br>" );out.println( val + "<br>" );val = pageContext.findAttribute( pageContext.EXCEPTION );val = pageContext.findAttribute( pageContext.EXCEPTION );out.println( val + "<br>" );out.println( val + "<br>" );val = pageContext.findAttribute( pageContext.OUT );val = pageContext.findAttribute( pageContext.OUT );out.println( val + "<br>" );out.println( val + "<br>" );val = pageContext.findAttribute( pageContext.PAGECONTEXT );val = pageContext.findAttribute( pageContext.PAGECONTEXT );out.println( val + "<br>" ); out.println( val + "<br>" );
%>%></body></html></body></html>
7979
JSP Standard Action Tags JSP Standard Action Tags (XML format)(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.
8080
JSP Action tags (Contd)JSP Action tags (Contd) Standard action tags start with Standard action tags start with
the namespace prefix the namespace prefix jspjsp followed by a colon and then by followed by a colon and then by tag name.tag name.
Ex: <jsp:param>Ex: <jsp:param> Actions may have attributes and Actions may have attributes and
tag bodies.tag bodies.
8181
Handling of ActionsHandling of ActionsJSP translators treat action tags as JSP translators treat action tags as
tokens that must be replaced with tokens that must be replaced with
Java code.Java code.Code for actions are defined in a Code for actions are defined in a
tag library.tag library.The translator simply replaces The translator simply replaces
action tags with output of the code action tags with output of the code
that is referenced by the action.that is referenced by the action.
8282
Handling of Actions…Handling of Actions… Ex: The tag Ex: The tag <jsp:useBean id=“test” <jsp:useBean id=“test”
class=“one.two.Tester”>class=“one.two.Tester”>
will be replaced withwill be replaced withObject test = (one.two.Tester) Object test = (one.two.Tester)
java.beans.Beans.instantiate( java.beans.Beans.instantiate(
this.getClass().getClassLoader(), this.getClass().getClassLoader(),
“one.two.Tester” );“one.two.Tester” );
8383
Action tagsAction tags Following action tags are available:Following action tags are available: <jsp:useBean><jsp:useBean> <jsp:getProperty><jsp:getProperty> <jsp:setProperty><jsp:setProperty>
<jsp:param><jsp:param> <jsp:forward><jsp:forward> <jsp:include><jsp:include> <jsp:plugin><jsp:plugin>
8484
useBean action taguseBean 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 />
8585
Attributes in useBean Attributes in useBean tagtag
AttributAttributee
FunctionFunction
idid Name used to refer the bean Name used to refer the bean within the page. Must be within the page. Must be unique.unique.
scope scope pagepage/request/session//request/session/application.application.
classclass Fully qualified bean class name.Fully qualified bean class name.
beanNambeanNamee
Bean name as per bean spec.Bean name as per bean spec.
typetype Reference type (super class or Reference type (super class or same type).same type).
8686
Attributes in useBean Attributes in useBean tagtag
Possible combination of attributes in Possible combination of attributes in useBean tag:useBean tag:
classclass Creates an instance of given classCreates an instance of given class class, typeclass, type Creates an instance of given Creates an instance of given
class; the bean will have the given type.class; the bean will have the given type. beanName, typebeanName, type Creates an instance of Creates an instance of
given bean, bean will have the given type.given bean, bean will have the given type. typetype if an object of the given type if an object of the given type
exists in the session, the id will refer that exists in the session, the id will refer that object.object.
8787
setProperty action tagsetProperty 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:namepropertyparamvalue
8888
Attributes in setProperty Attributes in setProperty tagtag
AttributAttributee
DescriptionDescription
namename Bean id specified in useBean.Bean id specified in useBean.
propertyproperty Name of the property to be set. Name of the property to be set. If individual bean property is If individual bean property is specified, respective setter method specified, respective setter method will be invoked.will be invoked.If *, client request parameter with If *, client request parameter with same name as bean property will be same name as bean property will be used to set the values.used to set the values.
paramparam Client request parameter whose value Client request parameter whose value will be used to set the value.will be used to set the value.
valuevalue Value to be assigned to the property.Value to be assigned to the property.
8989
Attributes in setProperty Attributes in setProperty tagtag
The name and property attributes The name and property attributes
are mandatory.are mandatory. param and value attributes are param and value attributes are
mutually exclusive.mutually exclusive. If param and value are not used, If param and value are not used,
the tag attempts to use value of the tag attempts to use value of
the request parameter with same the request parameter with same
name.name.
9090
getProperty action taggetProperty action tag•It allows to retrieve the value of a bean property.
•Syntax:<jsp:getProperty
attr_name=attri_val />
Attributes:name->bean id specified in useBean.property-> property whose value is to
retrieved.
9191
Bean access code 1 Bean access code 1 (bean)(bean)
package test;
public class StudentBean{
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; }
}
test/StudentBean.java
9292
Bean access code 1 Bean access code 1 (JSP)(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>
9393
Beans and Form Beans and Form processingprocessing
package test2;package test2;
public class UserData public class UserData {{ String username;String username; String email;String email; int age;int age;
public void setUsername( String value ){ username = value; }public void setUsername( String value ){ username = value; }
public void setEmail( String value ){ email = value; }public void setEmail( String value ){ email = value; }
public void setAge( int value ){ age = value; }public void setAge( int value ){ age = value; }
public String getUsername() { return username; }public String getUsername() { return username; }
public String getEmail() { return email; }public String getEmail() { return email; }
public int getAge() { return age; }public int getAge() { return age; }}}
UserData.java
9494
Beans and Form Beans and Form processingprocessing<HTML><HTML> <BODY><BODY>
<FORM METHOD=POST ACTION="beantest.jsp"><FORM METHOD=POST ACTION="beantest.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR>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 e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR>
What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4>What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4>
<P><INPUT TYPE=SUBMIT><P><INPUT TYPE=SUBMIT>
</FORM></BODY></FORM></BODY> </HTML></HTML>
<jsp:useBean id="user" class="test2.UserData" scope="session"/><jsp:useBean id="user" class="test2.UserData" scope="session"/>
<jsp:setProperty name="user" property="*"/> <jsp:setProperty name="user" property="*"/>
<HTML><HTML> <BODY><BODY> <A HREF=result.jsp>Continue</A><A HREF=result.jsp>Continue</A> </BODY></BODY></HTML></HTML>
<jsp:useBean id="user" class="test2.UserData" scope="session"/> <jsp:useBean id="user" class="test2.UserData" scope="session"/>
<HTML><HTML> <BODY><BODY>
The following data were received by the client <BR>The following data were received by the client <BR>
Name: <%= user.getUsername() %><BR>Name: <%= user.getUsername() %><BR>
Email: <%= user.getEmail() %><BR>Email: <%= user.getEmail() %><BR>
Age: <%= user.getAge() %><BR>Age: <%= user.getAge() %><BR>
</BODY></BODY> </HTML></HTML>
beantest.jsp
test.html
result.jsp
9595
Another ExampleAnother Examplepackage test3;package test3;
public class Userpublic class User{{
private String id;private String id;private String surname;private String surname;
public void setId( String id ){public void setId( String id ){ this.id = id;this.id = id; }}public String getId(){public String getId(){ return id;return id; }}public void setSurname( String surname ) {public void setSurname( String surname ) {this.surname = surname;this.surname = surname; }}public String getSurname( ){public String getSurname( ){ return surname;return surname;
}}}}
9696
Another ExampleAnother Example<jsp:useBean id="userA" class="test3.User" /><jsp:useBean id="userA" class="test3.User" />
<jsp:setProperty name="userA" property="surname" value="Smith" /><jsp:setProperty name="userA" property="surname" value="Smith" /><jsp:setProperty name="userA" property="id" value="<%= 32 + 45 + "45" %>" /><jsp:setProperty name="userA" property="id" value="<%= 32 + 45 + "45" %>" />
Your data are as follows : <br>Your data are as follows : <br>
ID : <jsp:getProperty name="userA" property="id" />ID : <jsp:getProperty name="userA" property="id" /><br><br>SURNAME : <jsp:getProperty name="userA" property="surname" />SURNAME : <jsp:getProperty name="userA" property="surname" />
9797
include action taginclude 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)
9898
How include action How include action worksworks
1.1. Original JSP file stops processing and Original JSP file stops processing and
passes the request to included file. passes the request to included file.
2.2. The included file generates its The included file generates its
response.response.
3.3. Response of the included file is Response of the included file is
returned to the calling JSP, which returned to the calling JSP, which
proceeds with its processing and proceeds with its processing and
generates the final response.generates the final response.
9999
Sample CodeSample 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>
100100
forward action tagforward 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/>
101101
How forward action How forward action worksworks Original JSP file stops processing and Original JSP file stops processing and
passes the request to forwarded passes the request to forwarded component.component.
Forwarded component generates the Forwarded component generates the final response.final response.
Note: Note: Execution never returns to the calling Execution never returns to the calling
page.page. Only one effective forward action is Only one effective forward action is
valid in a JSP document, later forward valid in a JSP document, later forward actions are ignored. actions are ignored.
102102
Sample CodeSample Code<HTML><HEAD><TITLE>Example Of The forward Action</TITLE></HEAD><BODY>
<% if (Math.random() > .5) { %>
<jsp:forward page=“one.jsp" /><% } else { %>
<jsp:forward page="two.jsp" /><% } %><%= System.getProperties() %>
</BODY></HTML>
103103
param action tagparam 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:paramname->namevalue->value
>..
</jsp:include>
104104
plugin action tagplugin action tag• It is used to embed objects for execution on client
• It is similar to <applet> tag• Syntax:
<jsp:plugin type->applet/beancode->class namecodebase->codebasewidth->width height-
>heightalign->alignmentarchive->archive listnspluginurl->urliepluginurl->url
/>
105105
DirectivesDirectives Directives give instructions to the JSP Directives give instructions to the JSP
container to be interpreted at translation container to be interpreted at translation time.time.
The general Syntax:The general Syntax:
<%@ directivename attribute=“value” <%@ directivename attribute=“value” attribute=”value”%>attribute=”value”%>
There are 3 directives There are 3 directives The The page page directivedirective The The includeinclude directive directive The The taglibtaglib directive directive
106106
Page DirectivePage DirectiveDefines attributes applicable to the entire JSP page.Defines attributes applicable to the entire JSP page. <%@ page atribute_name=attribute_value %><%@ page atribute_name=attribute_value %> Possible attributesPossible attributes
language=“java”language=“java” extends=“package.class”extends=“package.class” import=“package.*, package.class,…”import=“package.*, package.class,…” session=“true”session=“true” buffer=“8kb”buffer=“8kb” autoFlush=“true”autoFlush=“true” isThreadSafe=“true”isThreadSafe=“true” info=“text”info=“text” errorPage=“relativeURL”errorPage=“relativeURL” isErrorPage=“false”isErrorPage=“false” contentType=“mimeType”contentType=“mimeType” pageEncoding=encodingpageEncoding=encoding
Note: The extends attribute is recommended not to be used.Note: The extends attribute is recommended not to be used.
107107
Page Directive - DetailsPage Directive - DetailsAttribute
info
language
contentType
extends
import
session
buffer
autoFlush
isThreadSafe
errorPage
isErrorPage
Value
Text string
Scripting lang
MIME type,
Class name
Packages(s)
Boolean flag
Size or none
Boolean flag
Boolean flag
Local URL
Boolean flag
Default
None
“java”
“text’html”
None
None
“true”
Server specific
“true”
“true”
None
“false”
info=“Registration form”
language=“java”
contentType=“text/java”
extends=“com.gui.MyGUI”
import=“java.net.URL”
session=“true”
buffer=“12kb” buffer=“false”
autoFlush=“false”
isTheadSafe=“true”
errorPage=“msg/failed.jsp”
isErrorPage=“false”
multiple imports separated by “,”
Example
108108
Sample codeSample code<html>
<body><%@page info="jaa re bakra" %>
<%= getServletInfo() %></body>
</html>
<html> <body><!--
<%= "hello" %><%@page info="haal chaal kya khabar" %>
--><%= getServletInfo() %>
</body> </html>
109109
Handling Exceptions using Handling Exceptions using errorPageerrorPage<html> <body>
well come to error test<%@page errorPage="error.jsp" %>
<% int x = 10, y = 0; out.println( x/y );out.println( "all is well" );
%></body> </html>
<html> <body>Hai how r u<br/><%@page isErrorPage="true" %><br><% out.println ( "error " + exception ); %><br/> <br/>Hello am fine
</body> </html>
error_test.jsp
error.jsp
110110
include Directiveinclude 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" %>
111111
Sample CodeSample Code<html>
<body>Hi, How r u<%@ include file="one.jsp" %>Hi, am doing fine
</body></html>
<html><body>
<b><%= "Hello World" %>
</b><h1>
<%= "Hello World" %></h1>
</body></html>
two.jsp
one.jsp
112112
include directive vs include include directive vs include actionaction
directivedirective actionactionIncluded at JSP Included at JSP translation time.translation time.
Included at JSP Included at JSP request time.request time.
Inclusion is static Inclusion is static in nature.in nature.
Inclusion is Inclusion is dynamic.dynamic.
Recommended for Recommended for static/template static/template data.data.
Web component Web component usage usage recommended.recommended.
Cannot pass Cannot pass parameters.parameters.
Can pass Can pass parameters using parameters using <param> action.<param> action.
113113
Tag librariesTag libraries
<taglib> <taglib> directivedirective
114114
Tag LibrariesTag Libraries JSP Tags can be of two types:JSP Tags can be of two types:
Predefined tags:Predefined tags: They have They have jsp:jsp:
asas prefix. Ex: jsp:include.prefix. Ex: jsp:include. Custom tags:Custom tags: They are external, They are external,
user defined tag library.user defined tag library. The ability to define custom tags The ability to define custom tags
were made possible in JSP 1.1were made possible in JSP 1.1
115115
Tag LibraryTag Library It is a collection of custom actions/tags, It is a collection of custom actions/tags,
(portable elements) included in a JSP page.(portable elements) included in a JSP page. Defining custom tags involve:Defining custom tags involve:
Development of tag handlers for the tag.Development of tag handlers for the tag. Declaration of tag in tag library descriptor.Declaration of tag in tag library descriptor.
A tag library defines a set of related, custom A tag library defines a set of related, custom tags and links them to objects (tag handlers) tags and links them to objects (tag handlers) that implements functionality for the tags. that implements functionality for the tags.
JSP container uses TLD to interpret/handle JSP container uses TLD to interpret/handle taglib directives inside JSP documents.taglib directives inside JSP documents.
116116
• 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.
Advantages of Tag Library
117117
taglib Directivetaglib Directive•It allows us to access user-defined/custom tags in a JSP.
•Syntax:<%@ taglib
uri=“tld uri” prefix=“unique name”
%>
•Both attributes are mandatory.•More than one taglib directive can be used in the same JSP.
118118
Attribute uriAttribute uri TLD files are stored in WEB-INF directory of WAR or TLD files are stored in WEB-INF directory of WAR or in a subdirectory of WEB-INF.in a subdirectory of WEB-INF.
You can reference a TLD directly or indirectly. Ex:You can reference a TLD directly or indirectly. Ex: Direct referenceDirect reference
<%@ taglib uri="/WEB-INF/one.tld" prefix="tt" %><%@ taglib uri="/WEB-INF/one.tld" prefix="tt" %> Indirect reference (uses a short logical name)Indirect reference (uses a short logical name)
<%@ taglib uri="/aab" prefix="tt" %><%@ taglib uri="/aab" prefix="tt" %> Logical name is mapped to absolute location in Logical name is mapped to absolute location in
deployment descriptor using following entries:deployment descriptor using following entries:
<taglib><taglib>
<taglib-uri>/aab</taglib-uri><taglib-uri>/aab</taglib-uri>
<taglib-location>/web-inf/one.tld</taglib-location><taglib-location>/web-inf/one.tld</taglib-location>
</taglib></taglib>
119119
•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.
Custom tags and TLD
120120
Custom tags and Custom tags and TLDTLD Container takes necessary action Container takes necessary action
when custom tag is encountered.when custom tag is encountered. When a JSP page containing a custom When a JSP page containing a custom
tag is translated into a servlet, the tag is translated into a servlet, the tag is converted to operations on the tag is converted to operations on the respective tag handler.respective tag handler.
The web container then invokes The web container then invokes those operations when the JSP those operations when the JSP page’s servlet is executed.page’s servlet is executed.
121121
TLD formatTLD format<?xml version="1.0"><!DOCTYPE taglib SYSTEM "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"><taglib>
<tlib-version> version (M) </tlibversion><jsp-version> compatible jsp version (O)
</jspversion><short-name> document name (M) </shortname><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>
122122
TLD formatTLD format<tag><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)</body-content><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>..... </attribute>
</tag>
123123
TLD Tag TLD Tag DescriptionDescription
TagTag DescriptionDescription<tlibversion<tlibversion>>
Version number of library. (Must)Version number of library. (Must)
<jspversion<jspversion>>
Compliant JSP version.Compliant JSP version.
<shortname<shortname>>
Simple default name. Preferred Simple default name. Preferred prefix value in taglib directive. prefix value in taglib directive. (Must)(Must)
<uri><uri> Unique uri of the TLD document.Unique uri of the TLD document.
<description<description>>
Description/comments about TLD.Description/comments about TLD.
<tag><tag> Contains elements describing the Contains elements describing the tag.tag.
General Description elements/tags
124124
TLD Tag DescriptionTLD Tag DescriptionTags within the <tag> tag.
TagTag DescriptionDescription
<name><name> Name of the tagName of the tag
<tag-<tag-class>class>
Full class name of tag handler.Full class name of tag handler.
<tei-<tei-class>class>
Subclass of TagExtraInfo.Subclass of TagExtraInfo.
<body-<body-content>content>
Specifies whether tag can have Specifies whether tag can have content.content.Can be one of the following:Can be one of the following:tagdependent tagdependent :- contains non-jsp :- contains non-jsp code.code.JSPJSP :- body contains JSP code. :- body contains JSP code.emptyempty :- no body for this tag. :- no body for this tag.
<variable<variable>>
Scripting variable information. Scripting variable information.
<attribute<attribute>>
Defines attributes for the tag.Defines attributes for the tag.
125125
TLD Tag TLD Tag DescriptionDescriptionTags within the <attribute> tag.
TagTag DescriptionDescription<name><name> Defines attribute name.Defines attribute name.
<required><required> Specifies whether attribute is Specifies whether attribute is optional or not. (default – false)optional or not. (default – false)
Values - true/false/yes/noValues - true/false/yes/no
<rtexprvalue<rtexprvalue>>
Specifies whether the attribute Specifies whether the attribute value can be run time expression value can be run time expression or static. or static.
Values - true/false/yes/noValues - true/false/yes/no
<type><type> Specifies fully qualified data type.Specifies fully qualified data type.
(Static values are always of type (Static values are always of type String).String).
126126
TLD Tag TLD Tag DescriptionDescription
TagTag DescriptionDescription<name-<name-given>given>
The variable name as a constant.The variable name as a constant.
<name-from-<name-from-attribute>attribute>
Attribute name whose translation-Attribute name whose translation-timetime
value will give name of the value will give name of the variable. variable.
One among name-given orOne among name-given orname-from-attribute is mandatory.name-from-attribute is mandatory.
<variable-<variable-class>class>
Fully qualified class name (type) of Fully qualified class name (type) of the variable. java.lang.String is the variable. java.lang.String is default.default.
<declare><declare> Whether the variable refers to a Whether the variable refers to a new object. True is default.new object. True is default.
<scope><scope> Scope of variable. NESTED is Scope of variable. NESTED is default. default.
Tags within the <variable> tag.
127127
TLD Tag DescriptionTLD Tag DescriptionValue Value Availability Availability Methods Methods NESTED NESTED Between start tag Between start tag
and end tag and end tag In doInitBody and In doInitBody and doAfterBody if tag doAfterBody if tag handler implements handler implements BodyTag; otherwise, in BodyTag; otherwise, in doStartTag.doStartTag.
AT_BEGIN AT_BEGIN From start tag until From start tag until end of the page end of the page
doInitBody, doInitBody, doAfterBody & doAfterBody & doEndTag id tag doEndTag id tag handler implements handler implements BodyTag; otherwise, in BodyTag; otherwise, in doStartTag & doStartTag & doEndTag.doEndTag.
AT_END AT_END After end tag until After end tag until end of the page end of the page
In doEndTag.In doEndTag.
Possible values for <scope> tag within <variable> tag
128128
Code – tld fileCode – tld file<?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<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>
129129
Code – Java classCode – Java classpackage test;
import java.util.Date;import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;
public class DateClass extends TagSupport{
public int doEndTag() throws JspException{
try{Date dt = new Date();String dt_str = "" + dt;pageContext.getOut().write( dt_str );
}catch( Exception e) { System.out.println( e ); }return EVAL_PAGE;
}}
130130
Code – Jsp fileCode – Jsp file<%@ page language="java" %><%@ taglib uri="CurrentDate.tld" prefix="date" %><html><body>
<h1> The date & time now is : <date:today /> </h1></body></html>
131131
CustomCustom
Tag typesTag types
132132
Simple TagsSimple Tags A simple tag contains no body and A simple tag contains no body and
no attributes.no attributes. Ex: <prefix_name:tag_name />Ex: <prefix_name:tag_name />
It would have the following entry It would have the following entry in the respective TLD:in the respective TLD:
<body-content>empty</body-<body-content>empty</body-content>content>
133133
Tags With AttributesTags With Attributes A custom tag can have attributes listed in A custom tag can have attributes listed in
start tag having syntax attr="value". start tag having syntax attr="value".
Attributes customize behavior of a custom Attributes customize behavior of a custom tag just as parameters customize the tag just as parameters customize the behavior of a method. behavior of a method.
Attribute value can be a String constant or Attribute value can be a String constant or a runtime expression. Ex:a runtime expression. Ex:
1.1. <prefix_name:tag_name attr=“val" /><prefix_name:tag_name attr=“val" />
2.2. <prefix_name:tag_name attr1="<<prefix_name:tag_name attr1="<%=bookDB.getBooks()%>" %=bookDB.getBooks()%>" attrib2="val" />attrib2="val" />
134134
Tags with BodiesTags with Bodies A custom tag can contain custom and core A custom tag can contain custom and core
tags, scripting elements, HTML text, and tags, scripting elements, HTML text, and tag-dependent body content between the tag-dependent body content between the start and end tag.start and end tag.
Ex:Ex:
<prefix_name:tag_name attrib_name="val" /><prefix_name:tag_name attrib_name="val" />
<% cart.clear(); %><% cart.clear(); %>
<font color="#ff0000" size="+2"><strong> <font color="#ff0000" size="+2"><strong>
You just cleared your shopping cart! You just cleared your shopping cart!
</strong><br> <br></font></strong><br> <br></font>
</prefix_name:tag_name></prefix_name:tag_name>
135135
Tags That Define Tags That Define Scripting VariablesScripting Variables
A custom tag can define a variable that A custom tag can define a variable that can be used in scripts within a page.can be used in scripts within a page.
1)<tt:lookup id="tx" type="UserTransaction" 1)<tt:lookup id="tx" type="UserTransaction" name="java:comp/UserTransaction" />name="java:comp/UserTransaction" />
<% tx.begin(); %><% tx.begin(); %>
2) <tt:define id="book" name="bookDB" />2) <tt:define id="book" name="bookDB" />
<jsp:getProperty name="book" <jsp:getProperty name="book" property="title">property="title">
136136
Cooperating TagsCooperating Tags Custom tags can cooperate with each Custom tags can cooperate with each
other through shared objects. In the other through shared objects. In the following example, tag1 creates an following example, tag1 creates an object called obj1, which is then reused object called obj1, which is then reused by tag2. by tag2.
<tt:tag1 attr1="obj1" value1="value" /><tt:tag1 attr1="obj1" value1="value" /><tt:tag2 attr1="obj1" /><tt:tag2 attr1="obj1" />
Also an object created by enclosing tag Also an object created by enclosing tag is available to all inner tags. is available to all inner tags.
<tt:outerTag><tt:outerTag> <tt:innerTag /><tt:innerTag /></tt:outerTag></tt:outerTag>
137137
Tag HandlersTag Handlers It is a Java class that implements It is a Java class that implements
behavior of a custom tag.behavior of a custom tag. It is invoked by Web container to It is invoked by Web container to
evaluate a custom tag during execution evaluate a custom tag during execution of JSP page that references the tag. of JSP page that references the tag.
They must implement either Tag or They must implement either Tag or BodyTag interface, preferably via BodyTag interface, preferably via TagSupport and BodyTagSupport TagSupport and BodyTagSupport classes respectively.classes respectively.
Tag handlers will be referenced in TLD Tag handlers will be referenced in TLD files.files.
138138
Tag Handlers…Tag Handlers… When a JSP page containing a custom tag is When a JSP page containing a custom tag is
translated into a servlet, the tag is translated into a servlet, the tag is
converted to operations on tag handler. The converted to operations on tag handler. The
container then invokes those operations container then invokes those operations
when the JSP page's Servlet is executed.when the JSP page's Servlet is executed. Note: A tag handler has access to an API Note: A tag handler has access to an API
that allows it to communicate with the JSP that allows it to communicate with the JSP
page. Entry point to the API is PageContext, page. Entry point to the API is PageContext,
through which a tag handler can retrieve all through which a tag handler can retrieve all
implicit objects accessible from a JSP page.implicit objects accessible from a JSP page.
139139
Package Package
javax.servlet.jsp.tagjavax.servlet.jsp.tagextext
140140
Interface HierarchyInterface Hierarchy
141141
TagTagIt defines a handler for simple tags It defines a handler for simple tags which does not manipulate tag body.which does not manipulate tag body.
It specifies a framework (protocol) for It specifies a framework (protocol) for interaction between a Tag handler interaction between a Tag handler and JSP page implementation class.and JSP page implementation class.
i.e. it defines the life cycle methods i.e. it defines the life cycle methods to be invoked at start and end tag.to be invoked at start and end tag.
It specifies accessor methods for It specifies accessor methods for pageContext and parent properties.pageContext and parent properties.
142142
Tag – Method Tag – Method summarysummary void void setPageContext(PageContext pc) setPageContext(PageContext pc)
void void setParent(Tag t)setParent(Tag t) int int doStartTag() doStartTag() int int doEndTag() doEndTag() Tag Tag getParent() getParent() void void release() release()
JSP page implementation object JSP page implementation object invokes setPageContext and setParent, invokes setPageContext and setParent, in that order, before invoking in that order, before invoking doStartTag() or doEndTag().doStartTag() or doEndTag().
143143
Tag - Field Summary Tag - Field Summary static int static int SKIP_BODY SKIP_BODY Skip body evaluation. Skip body evaluation. static int static int EVAL_BODY_INCLUDEEVAL_BODY_INCLUDE Evaluate the tag body.Evaluate the tag body.
static int static int SKIP_PAGE SKIP_PAGE Skip the rest of the page. Skip the rest of the page. static int static int EVAL_PAGEEVAL_PAGE Continue evaluating the page. Continue evaluating the page.
144144
•If the TLD file indicates that the action tag must be empty, then doStartTag() must return SKIP_BODY.
•Otherwise, the doStartTag() method may return SKIP_BODY or EVAL_BODY_INCLUDE.
•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.
Tag - Field usage
145145
Sample codeSample codeA simple tag for example <abc:simple /> A simple tag for example <abc:simple />
would be implemented by the following tag would be implemented by the following tag handler:handler:
public SimpleTag public SimpleTag extends TagSupportextends TagSupport {{ public int doStartTag() throws JspException public int doStartTag() throws JspException
{{ try {try {
pageContext.getOut().print("Hello.");pageContext.getOut().print("Hello."); } catch (Exception ex) } catch (Exception ex)
{{pageContext.getOut().print("SimpleTag: " + pageContext.getOut().print("SimpleTag: " +
ex.getMessage());ex.getMessage()); }} return SKIP_BODY;return SKIP_BODY; }} public int doEndTag() { return EVAL_PAGE; }public int doEndTag() { return EVAL_PAGE; }}}
146146
IterationTagIterationTag It extends Tag by defining one It extends Tag by defining one
additional method ( doAfterBody() ) additional method ( doAfterBody() ) that processes tag body.that processes tag body.
The doAfterBody() is invoked after The doAfterBody() is invoked after every body evaluation if doStartTag() every body evaluation if doStartTag() returns EVAL_BODY_INCLUDE.returns EVAL_BODY_INCLUDE.
If it returns EVAL_BODY_AGAIN, then If it returns EVAL_BODY_AGAIN, then the body will be reevaluated.the body will be reevaluated.
If it returns SKIP_BODY, then the body If it returns SKIP_BODY, then the body reevaluation will be skipped and reevaluation will be skipped and doEndTag() is invoked.doEndTag() is invoked.
147147
IterationTag MembersIterationTag Members
Field Summary Field Summary static int static int EVAL_BODY_AGAINEVAL_BODY_AGAIN
Request reevaluation of Request reevaluation of body content. body content.
Method Summary Method Summary int doAfterBody()int doAfterBody()
Process body content. Process body content.
148148
BodyTagBodyTag It extends IterationTag and defines It extends IterationTag and defines
additional methods that let a tag additional methods that let a tag
handler to manipulate body content by handler to manipulate body content by
providing buffering.providing buffering.
While implementing BodyTag, the While implementing BodyTag, the
doStartTag() can return SKIP_BODY, doStartTag() can return SKIP_BODY,
EVAL_BODY_INCLUDE or EVAL_BODY_INCLUDE or
EVAL_BODY_BUFFERED.EVAL_BODY_BUFFERED.
149149
•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.
BodyTag…
150150
int EVAL_BODY_BUFFERED
Request the creation of new buffer, a BodyContent on which to evaluate the body of this tag.
int EVAL_BODY_TAG
Deprecated as of Java JSP API 1.2, use BodyTag.EVAL_BODY_BUFFERED or IterationTag.EVAL_BODY_AGAIN.
Field Summary
151151
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() returns EVAL_BODY_BUFFERED
Method Summary
152152
•If TLD file indicates that action must
be empty, then doStartTag() must
return SKIP_BODY.
•Otherwise, doStartTag() may return
SKIP_BODY, EVAL_BODY_INCLUDE, or
EVAL_BODY_BUFFERED.
•If SKIP_BODY is returned, body is not
evaluated and doEndTag() is invoked.
BodyTag - Field usage
153153
•If EVAL_BODY_INCLUDE is returned,
setBodyContent() and doInitBody() will not
be invoked, the body is evaluated and
"passed through" to the current out,
doAfterBody() followed by doEndTag() is
invoked.
•If EVAL_BODY_BUFFERED is returned,
setBodyContent() followed by doInitBody()
is invoked, the body is evaluated,
doAfterBody() followed by doEndTag() is
invoked.
BodyTag - Field usage…
154154
Interface TryCatchFinally•It provides as 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.
155155
Class HierarchyClass Hierarchy
156156
Class TagSupportClass TagSupport Is a utility class to be extended by new Is a utility class to be extended by new
tag handlers instead of implementing tag handlers instead of implementing
Tag/IterationTag.Tag/IterationTag.
It implements Tag and IterationTag and It implements Tag and IterationTag and
adds additional methods including getter adds additional methods including getter
methods for the properties in Tag. methods for the properties in Tag.
It is further extended by BodyTagSupport.It is further extended by BodyTagSupport.
It has one static method that facilitates It has one static method that facilitates
coordination among cooperating tags. coordination among cooperating tags.
157157
Field Summary Field Summary protected String protected String id id protected PageContext protected PageContext pageContextpageContext
Fields inherited from TagFields inherited from Tag EVAL_BODY_INCLUDEEVAL_BODY_INCLUDE EVAL_PAGEEVAL_PAGE SKIP_BODYSKIP_BODY SKIP_PAGESKIP_PAGE
Fields inherited from IterationTag Fields inherited from IterationTag EVAL_BODY_AGAINEVAL_BODY_AGAIN
158158
Method Summary Method Summary int doStartTag()int doStartTag() Default processing of start tag.Default processing of start tag. int doEndTag()int doEndTag() Default processing of end tag. Default processing of end tag. int doAfterBody()int doAfterBody() Default processing for a body. Default processing for a body.
static Tag findAncestorWithClass(Tag from, Class static Tag findAncestorWithClass(Tag from, Class klass)klass)
Find instance of given type closest to given tag. Find instance of given type closest to given tag.
String getId()String getId()The value of the id attribute of this tag; or null.The value of the id attribute of this tag; or null. void setId(String id)void setId(String id) Set the id attribute for this tag.Set the id attribute for this tag.
159159
Method Summary…Method Summary… Tag getParent()Tag getParent() The Tag instance most closely enclosing this tag The Tag instance most closely enclosing this tag
instance.instance. void setParent(Tag t)void setParent(Tag t) Set the nesting tag of this tag.Set the nesting tag of this tag.
Object getValue(String k)Object getValue(String k) Get a the value associated with a key.Get a the value associated with a key. Enumeration getValues()Enumeration getValues() void setValue(String k, Object o) void setValue(String k, Object o) void removeValue(String k) void removeValue(String k)
void setPageContext(PageContext pageContext) void setPageContext(PageContext pageContext)
void release()void release()
160160
Class BodyTagSupportClass BodyTagSupport A base class for defining tag handlers A base class for defining tag handlers
implementing BodyTag.implementing BodyTag.
It implements BodyTag, IterationTag, It implements BodyTag, IterationTag,
Serializable and Tag interfacesSerializable and Tag interfaces
It adds additional methods including It adds additional methods including
getter methods for bodyContent getter methods for bodyContent
property and methods to get the property and methods to get the
previous out (JspWriter).previous out (JspWriter).
161161
Field SummaryField Summary protected BodyContent bodyContentprotected BodyContent bodyContent Fields inherited from TagSupportFields inherited from TagSupport IdId pageContextpageContext Fields inherited from interface TagFields inherited from interface Tag EVAL_BODY_INCLUDEEVAL_BODY_INCLUDE EVAL_PAGEEVAL_PAGE SKIP_BODY, SKIP_PAGESKIP_BODY, SKIP_PAGE Fields inherited from interface IterationTag Fields inherited from interface IterationTag EVAL_BODY_AGAINEVAL_BODY_AGAINFields inherited from interface BodyTag Fields inherited from interface BodyTag EVAL_BODY_BUFFEREDEVAL_BODY_BUFFERED EVAL_BODY_TAG (Deprecated)EVAL_BODY_TAG (Deprecated)
162162
Method Summary Method Summary int doStartTag() int doStartTag() Default processing of start tag.Default processing of start tag. void setBodyContent(BodyContent b)void setBodyContent(BodyContent b) Prepare for evaluation of the body; store Prepare for evaluation of the body; store
bodyContent.bodyContent. void doInitBody()void doInitBody() Prepare for body evaluation just before first Prepare for body evaluation just before first
body evaluation.body evaluation. int doAfterBody() int doAfterBody() After body evaluation.After body evaluation. int doEndTag()int doEndTag() Default processing of the end tag.Default processing of the end tag.
163163
Method Summary…Method Summary… BodyContent getBodyContent()BodyContent getBodyContent()
Get current bodyContent. Get current bodyContent.
JspWriter getPreviousOut()JspWriter getPreviousOut()
Get the out (JspWriter). Get the out (JspWriter).
void release() void release()
164164
Class BodyContentClass BodyContent It extends JspWriter.It extends JspWriter. It encapsulates evaluated body content. It encapsulates evaluated body content. Since it encapsulates the result of Since it encapsulates the result of
evaluation, it will not contain actions and evaluation, it will not contain actions and the like, but the result of their the like, but the result of their invocation.invocation.
Its buffer size is unbounded.Its buffer size is unbounded. A BodyContent is made available to a A BodyContent is made available to a
BodyTag through a setBodyContent() call. BodyTag through a setBodyContent() call. Tag handlers can use it until after the call Tag handlers can use it until after the call
to doEndTag(). to doEndTag().
165165
Method Summary Method Summary protected BodyContent(JspWriter e) protected BodyContent(JspWriter e)
void clearBody() void clearBody() abstract java.io.Reader getReader()abstract java.io.Reader getReader()
Return value of this BodyContent as a Reader. Return value of this BodyContent as a Reader. abstract String getString()abstract String getString()
Return value of the BodyContent as a String. Return value of the BodyContent as a String. abstract void writeOut(java.io.Writer out)abstract void writeOut(java.io.Writer out)
Write contents of this BodyContent into a Write contents of this BodyContent into a Writer. Writer.
166166
Class TagExtraInfoClass TagExtraInfo Optional class specified in the TLD to Optional class specified in the TLD to
describe additional translation-time describe additional translation-time information not described in the TLD.information not described in the TLD.
TagExtraInfo class must be TagExtraInfo class must be mentioned in TLD file.mentioned in TLD file.
This class can be used: This class can be used: to indicate that the tag defines scripting to indicate that the tag defines scripting
variables variables to perform translation-time validation of to perform translation-time validation of
the tag attributes. the tag attributes.
167167
Method Summary Method Summary TagInfo getTagInfo() TagInfo getTagInfo()
Get the TagInfo for this class. Get the TagInfo for this class. VariableInfo[] getVariableInfo(TagData data)VariableInfo[] getVariableInfo(TagData data)
information on scripting variables defined by information on scripting variables defined by the tag associated with this TagExtraInfo the tag associated with this TagExtraInfo instance. instance.
boolean isValid(TagData data) boolean isValid(TagData data)
Translation-time validation of the attributes. Translation-time validation of the attributes. void setTagInfo(TagInfo tagInfo)void setTagInfo(TagInfo tagInfo)
Set the TagInfo for this class. Set the TagInfo for this class.
168168
Class TagInfoClass TagInfo Tag information for a tag in a Tag Tag information for a tag in a Tag
Library; This class is instantiated Library; This class is instantiated from the TLD and is available only at from the TLD and is available only at translation time. translation time.
169169
Field Summary Field Summary static String BODY_CONTENT_EMPTY static String BODY_CONTENT_EMPTY static constant for getBodyContent() static constant for getBodyContent()
when it is empty when it is empty static String BODY_CONTENT_JSPstatic String BODY_CONTENT_JSP static constant for getBodyContent() static constant for getBodyContent()
when it is JSP when it is JSP static String static String
BODY_CONTENT_TAG_DEPENDENTBODY_CONTENT_TAG_DEPENDENT static constant for getBodyContent() static constant for getBodyContent()
when it is Tag dependent when it is Tag dependent
170170
Method Summary Method Summary String getTagName() String getTagName() String getTagClassName() String getTagClassName() TagExtraInfo getTagExtraInfo() TagExtraInfo getTagExtraInfo()
The instance (if any) for extra tag information The instance (if any) for extra tag information String getBodyContent() String getBodyContent() String getDisplayName() String getDisplayName() String getSmallIcon() String getSmallIcon() String getLargeIcon() String getLargeIcon() String getInfoString() String getInfoString()
171171
Method Summary…Method Summary… TagAttributeInfo[] getAttributes() TagAttributeInfo[] getAttributes() TagVariableInfo[] TagVariableInfo[]
getTagVariableInfos() getTagVariableInfos()
TagLibraryInfo getTagLibrary() TagLibraryInfo getTagLibrary()
boolean isValid(TagData data) boolean isValid(TagData data)
Translation-time validation of Translation-time validation of attributes.attributes.
172172
Class VariableInfoClass VariableInfo Provides information about scripting Provides information about scripting
variables.variables. This information is provided by This information is provided by
TagExtraInfo classes and it is used TagExtraInfo classes and it is used during translation of JSP. during translation of JSP.
173173
Member summaryMember summaryField Summary Field Summary static int AT_BEGIN static int AT_BEGIN static int AT_END static int AT_END static int NESTEDstatic int NESTED
Method Summary Method Summary String getVarName()String getVarName() String getClassName() String getClassName() boolean getDeclare() boolean getDeclare() int getScope() int getScope()
174174
Class TagVariableInfoClass TagVariableInfo Provides scripting variable information Provides scripting variable information
for a tag in a Tag Library.for a tag in a Tag Library.
This class is instantiated from the TLD This class is instantiated from the TLD
and is available only at translation and is available only at translation
time. time.
This information is only available in This information is only available in
JSP1.2JSP1.2
175175
Method SummaryMethod Summary String getNameGiven() String getNameGiven()
String getNameFromAttribute() String getNameFromAttribute()
String getClassName() String getClassName()
boolean getDeclare() boolean getDeclare()
int getScope() int getScope()
176176
Class TagAttributeInfoClass TagAttributeInfo Provides information about attributes Provides information about attributes
of a Tag, available at translation time. of a Tag, available at translation time. This class is instantiated from TLD file.This class is instantiated from TLD file. Only the information needed to Only the information needed to
generate code is included here.generate code is included here.
177177
Method SummaryMethod Summary String getName() String getName() boolean isRequired() boolean isRequired() boolean canBeRequestTime() boolean canBeRequestTime() String getTypeName() String getTypeName()
178178
Class TagLibraryInfoClass TagLibraryInfo Translation-time information Translation-time information
associated with a taglib directive, associated with a taglib directive, and its underlying TLD file. Most of and its underlying TLD file. Most of the information is directly from the the information is directly from the TLD, except for the prefix and the uri TLD, except for the prefix and the uri values used in the taglib directive.values used in the taglib directive.
179179
Field SummaryField Summary protected String tlibversion protected String tlibversion
protected String jspversionprotected String jspversion
protected String shortnameprotected String shortname
protected String uri protected String uri
protected String info protected String info
protected TagInfo[] tags protected TagInfo[] tags
180180
Method Summary Method Summary String getRequiredVersion() String getRequiredVersion() String getShortName() String getShortName() String getURI() String getURI() String getInfoString() String getInfoString()
TagInfo getTag(java.lang.String TagInfo getTag(java.lang.String
shortname) shortname) TagInfo[] getTags() TagInfo[] getTags()
181181
•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.
Class PageData
182182
•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)
Class TagAttributeInfo
183183
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.
Method Summary
184184
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)
Class TagData
185185
Writing Tag Writing Tag HandlersHandlers
186186
Simple tagsSimple tags Handler for simple tag must implement Handler for simple tag must implement
doStartTag and doEndTag methods of Tag doStartTag and doEndTag methods of Tag interface. interface.
Method doStartTag is invoked when the Method doStartTag is invoked when the start tag is encountered. start tag is encountered.
Method doStartTag must return SKIP_BODY Method doStartTag must return SKIP_BODY since simple tags have no body. since simple tags have no body.
Method doEndTag is invoked when the end Method doEndTag is invoked when the end tag is encountered. tag is encountered.
Method doEndTag needs to return Method doEndTag needs to return EVAL_PAGE if the rest of the page needs to EVAL_PAGE if the rest of the page needs to be evaluated; otherwise, it should return be evaluated; otherwise, it should return SKIP_PAGE. SKIP_PAGE.
187187
Simple tag - ExampleSimple tag - ExampleA simple tag A simple tag <tt:simple /><tt:simple /> would be implemented would be implemented by the following tag handler: by the following tag handler:
public SimpleTag extends TagSupport {public SimpleTag extends TagSupport { public int doStartTag() throws JspException {public int doStartTag() throws JspException { try {try { pageContext.getOut().print("Hello.");pageContext.getOut().print("Hello."); } catch (Exception ex) {} catch (Exception ex) { throw new JspTagException("SimpleTag: " + throw new JspTagException("SimpleTag: " + ex.getMessage());ex.getMessage()); }} return SKIP_BODY;return SKIP_BODY; }} public int doEndTag() { return EVAL_PAGE; }public int doEndTag() { return EVAL_PAGE; }}}
188188
Tags with Attributes Tags with Attributes In this case for each attribute, the Tag In this case for each attribute, the Tag
Handler must define a property as well as Handler must define a property as well as get and set methods that conform to get and set methods that conform to JavaBeans architecture conventions.JavaBeans architecture conventions.
Ex: Tag handler for following tag in JSP, Ex: Tag handler for following tag in JSP, <prefix:tag_name parameter="Clear"><prefix:tag_name parameter="Clear">contains the following declaration and contains the following declaration and
methods: methods: private String parameter = null;private String parameter = null;public String getParameter() public String getParameter() { return parameter; }{ return parameter; }public void setParameter(String parameter) public void setParameter(String parameter) { this.parameter = parameter; }{ this.parameter = parameter; }
189189
Attribute ValidationAttribute ValidationThe tag library documentation should describe The tag library documentation should describe
valid values for tag attributes.valid values for tag attributes.
During JSP translation, container enforces During JSP translation, container enforces
constraints contained in TLD for each attribute.constraints contained in TLD for each attribute.
Attributes passed to a tag can also be Attributes passed to a tag can also be
validated during translation using isValid validated during translation using isValid
method of a class derived from TagExtraInfo. method of a class derived from TagExtraInfo.
Method isValid is passed a TagData object, Method isValid is passed a TagData object,
which contains information about each which contains information about each
attribute.attribute.
190190
Attribute Validation using Attribute Validation using TagExtraInfoTagExtraInfo
The tag The tag <tt:twa attr1="value1"/><tt:twa attr1="value1"/> has the has the following TLD attribute element: following TLD attribute element:
<attribute><attribute>
<name>attr1</name><name>attr1</name>
<required>true</required><required>true</required>
<rtexprvalue>true</rtexprvalue><rtexprvalue>true</rtexprvalue>
</attribute></attribute>
This declaration indicates that the value of This declaration indicates that the value of attr1 can be determined at runtime. attr1 can be determined at runtime.
The following isValid method checks that the The following isValid method checks that the value of attr1 is a valid Boolean value.value of attr1 is a valid Boolean value.
191191
Attribute Validation…Attribute Validation…public class TEI extends TagExtraInfo public class TEI extends TagExtraInfo {{ public boolean isValid(Tagdata data) public boolean isValid(Tagdata data)
{{ Object o = data.getAttribute("attr1");Object o = data.getAttribute("attr1"); if (o != null ) if (o != null )
{{if if
( ((String)o).toLowerCase().equals("true") ) ( ((String)o).toLowerCase().equals("true") ) return true;return true;
elseelsereturn false;return false;
} else} elsereturn false;return false;
}}}}
192192
Tags with BodiesTags with Bodies A tag handler for a tag with body is A tag handler for a tag with body is
implemented differently depending implemented differently depending on whether the tag handler needs to on whether the tag handler needs to interact with the body or not. interact with the body or not.
A tag is said to interact with body A tag is said to interact with body content if the tag handler content if the tag handler reads/modifies body content.reads/modifies body content.
193193
Tag Handler Does Not Tag Handler Does Not Interact with Body Interact with Body If tag handler does not need to interact with If tag handler does not need to interact with
body, it should implement Tag interface or body, it should implement Tag interface or extend TagSupport. extend TagSupport.
If tag body needs to be evaluated, If tag body needs to be evaluated, doStartTag method must return doStartTag method must return EVAL_BODY_INCLUDE; otherwise it should EVAL_BODY_INCLUDE; otherwise it should return SKIP_BODY. return SKIP_BODY.
If a tag handler needs to iteratively evaluate If a tag handler needs to iteratively evaluate the body, it should implement IterationTag the body, it should implement IterationTag or extend TagSupport. or extend TagSupport.
It should return EVAL_BODY_AGAIN from the It should return EVAL_BODY_AGAIN from the doStartTag and doAfterBody methods if the doStartTag and doAfterBody methods if the body needs to be evaluated again.body needs to be evaluated again.
194194
Tag Handler Interacts with Tag Handler Interacts with BodyBody If tag handler needs to interact with body, it must If tag handler needs to interact with body, it must
implement BodyTag or extend BodyTagSupport.implement BodyTag or extend BodyTagSupport. Such handlers implement doInitBody and doAfterBody.Such handlers implement doInitBody and doAfterBody. These methods have access to BodyContent object, These methods have access to BodyContent object,
which provides several methods to read and write body. which provides several methods to read and write body. A tag handler can use BodyContent's getString or A tag handler can use BodyContent's getString or
getReader methods to extract body information and getReader methods to extract body information and writeOut(out) to write the body contents to out stream.writeOut(out) to write the body contents to out stream.
The parameter supplied to writeOut method is obtained The parameter supplied to writeOut method is obtained using tag handler's getPreviousOut method. using tag handler's getPreviousOut method.
This method ensures that a tag handler's results are This method ensures that a tag handler's results are available to an enclosing tag handler. available to an enclosing tag handler.
If tag body needs to be evaluated, doStartTag needs to If tag body needs to be evaluated, doStartTag needs to return EVAL_BODY_BUFFERED; otherwise, it should return EVAL_BODY_BUFFERED; otherwise, it should return SKIP_BODY.return SKIP_BODY.
195195
Tag Handler Interacts Tag Handler Interacts with Body…with Body…
doInitBody MethoddoInitBody Method It is called before body content is evaluated and It is called before body content is evaluated and
hence is generally used to perform any hence is generally used to perform any initialization that depends on body content.initialization that depends on body content.
doAfterBody MethoddoAfterBody Method It is called after the body content is evaluated.It is called after the body content is evaluated. Like doStartTag method, doAfterBody must return Like doStartTag method, doAfterBody must return
an indication of whether to continue evaluating an indication of whether to continue evaluating body. body.
Thus, if body should be evaluated again, Thus, if body should be evaluated again, doAfterBody should return EVAL_BODY_BUFFERED; doAfterBody should return EVAL_BODY_BUFFERED; otherwise, it should return SKIP_BODY.otherwise, it should return SKIP_BODY.
release Methodrelease Method A tag handler should release any private resources A tag handler should release any private resources
in the release method.in the release method.
196196
Tag Handler Interacts Tag Handler Interacts with Body…with Body… The tag handler below reads body content (which contains The tag handler below reads body content (which contains
a SQL query) and executes the query. Since body does not a SQL query) and executes the query. Since body does not need to be reevaluated, doAfterBody returns SKIP_BODY.need to be reevaluated, doAfterBody returns SKIP_BODY.
public class QueryTag extends BodyTagSupport public class QueryTag extends BodyTagSupport {{ public int doAfterBody() throws JspTagException public int doAfterBody() throws JspTagException
{{ BodyContent bc = getBodyContent();BodyContent bc = getBodyContent(); String query = bc.getString();String query = bc.getString();
try {try { Statement stmt = Statement stmt =
connection.createStatement();connection.createStatement(); ResultSet result = stmt.executeQuery(query);ResultSet result = stmt.executeQuery(query);
………….... } catch (SQLException e) } catch (SQLException e)
{{ throw new JspTagException("QueryTag: " + e); throw new JspTagException("QueryTag: " + e); }}
return SKIP_BODY;return SKIP_BODY; }}}}
197197
Tag Handler Interacts with Tag Handler Interacts with Body…Body…
body-content Elementbody-content Element For tags that have a body, body content type must For tags that have a body, body content type must
be specified using body-content element: be specified using body-content element:
<body-content>JSP/tagdependent</body-content><body-content>JSP/tagdependent</body-content> Body content containing custom/core tags, scripting Body content containing custom/core tags, scripting
elements, and HTML text is categorized as JSP. elements, and HTML text is categorized as JSP. All other types of body content--for example--SQL All other types of body content--for example--SQL
statements would be labeled tagdependent. statements would be labeled tagdependent.
Note: Value of body-content element does not affect Note: Value of body-content element does not affect body interpretation by tag handler; It is only body interpretation by tag handler; It is only intended to be used by an authoring tool for body intended to be used by an authoring tool for body content. content.
198198
Tags with scripting Tags with scripting variables variables A tag handler is responsible for creating or A tag handler is responsible for creating or
setting object referred by scripting variable setting object referred by scripting variable into a context accessible from the page. into a context accessible from the page.
This is done using method This is done using method pageContext.setAttribute( name, value, pageContext.setAttribute( name, value, scope)scope)
Typically an attribute passed to custom tag Typically an attribute passed to custom tag specifies name of the scripting variable specifies name of the scripting variable object; this name can be retrieved by invoking object; this name can be retrieved by invoking the attribute's get method described in Using the attribute's get method described in Using Scope Objects. Scope Objects.
199199
Tags with scripting Tags with scripting variablesvariables
Scripting variable value is retrieved Scripting variable value is retrieved using using pageContext.getAttribute( name, pageContext.getAttribute( name, scope). scope).
The usual procedure is that the tag The usual procedure is that the tag handler retrieves a scripting handler retrieves a scripting variable, performs some processing variable, performs some processing on the object, and then sets scripting on the object, and then sets scripting variable's value using variable's value using pageContext.setAttribute( name, pageContext.setAttribute( name, object)object)
200200
The table below summarizes object scopes.The table below summarizes object scopes.
NameName Accessible FromAccessible From LifetimeLifetime
pagepage Current pageCurrent page
Until response has been Until response has been sent back to user or sent back to user or request is passed to a request is passed to a new pagenew page
requestrequestCurrent and any Current and any included or forwarded included or forwarded pagespages
Until the response has Until the response has been sent back to the been sent back to the useruser
sessionsession
Current request and Current request and any subsequent any subsequent request from same request from same browser (subject to browser (subject to session lifetime)session lifetime)
Life of user's sessionLife of user's session
applicatioapplicationn
Current and any future Current and any future request from the same request from the same Web applicationWeb application
Life of the applicationLife of the application
201201
Providing Information about Providing Information about Scripting Variable Scripting Variable
The example below defines a scripting The example below defines a scripting variable book that is used for accessing variable book that is used for accessing book information: book information:
<bean:define id="book" name="bookDB" <bean:define id="book" name="bookDB" property="bookDetails“ property="bookDetails“ type="database.BookDetails"/>type="database.BookDetails"/>
<font color="red" size="+2"><font color="red" size="+2"> <%=messages.getString("CartRemoved")<%=messages.getString("CartRemoved")
%>%> <strong><jsp:getProperty name="book“ <strong><jsp:getProperty name="book“
property="title"/></strong> property="title"/></strong> <br> <br><br> <br></font></font>
202202
When the JSP page containing this tag is When the JSP page containing this tag is translated, the Web container generates code to translated, the Web container generates code to synchronize the scripting variable with the object synchronize the scripting variable with the object referenced by the variable. To generate the code, referenced by the variable. To generate the code, the Web container requires certain information the Web container requires certain information about the scripting variable: about the scripting variable:
Variable name Variable name Variable class Variable class Whether the variable refers to a new or existing Whether the variable refers to a new or existing
object object The availability of the variable. The availability of the variable.
There are two ways to provide this information: There are two ways to provide this information: by specifying the variable TLD subelement or by by specifying the variable TLD subelement or by defining a tag extra info class and including the defining a tag extra info class and including the tei-class element in the TLD. Using the variable tei-class element in the TLD. Using the variable element is simpler, but slightly less flexible. element is simpler, but slightly less flexible.
203203
Thank You