P. 1



|Views: 214|Likes:
Published by api-26457061

More info:

Published by: api-26457061 on Oct 14, 2008
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as PPT, PDF, TXT or read online from Scribd
See more
See less







Understanding JSP
•Java Server Pages is another server-side technology defined by Sun Microsystems to generate dynamic web content. •They are direct extension of servlets. •They are more efficient than servlets. •JSP is a type of server-side scripting language. •JSP program files have an extension .jsp 2

Understanding JSP
•They are HTML documents which are embedded with Java code using different JSP tags. •When compared with servlets they are unstructured and contains pieces of java code scattered through out an HTML file. •Since they are server-side applications, they have access to server resources such as servlets, javabeans, Ejbs and databases.

Advantages of JSP
•JSP’s being Java programs, they allow write-once, run-anywhere policy. •JSP tags are simple to understand, since they are similar to HTML and XML. •Since there is a standard, published API for JSP, and because of Java code portability, use of JSP is independent of hardware, OS or server software.

Advantages of JSP
• JSP being vendor-neutral, developers and system architects can select best-of-breed solutions at all stages of JSP deployment. • It has full access to the underlying J2SE APIs (database access, directory services, distributed computing, cryptography…). • Hence JSP is highly flexible and featurerich to create web-based applications.

Advantages of JSP
• Does not require server restart when the JSP program code changes. • Separation of roles into graphical content and dynamic content. • JSP’s being a modified way of writing servlets, they can provide all features/capabilities of a servlets.

JSP History
• Servlets first appeared as part of Sun’s Java Web Server (JWS), a Java based HTTP server in 1997. • Sun eventually released the Servlet technology as a standard Java extension. • JSP soon followed, with the first draft API specifications appearing in 1998.

JSP History
• JSP 1.0 Specification was released in June 1999 as a part of J2EE. • JSP 1.1 - Late 1999. • JSP 1.2 - 2001. • JSP 2.0 – 2003.

Third party vendor support
•RAD tools are now available to create dynamic web pages, using DnD approach. •Ability to create sophisticated JSP pages without seeing HTML tags, let alone Java code will enhance the productivity to a greater extent. •Ex: Drumbeat 2000 from Macromedia
IBM’s Visual Age for Java HomeSite from Allaire

WEB Server Platform Reusable components Memory leak protection Scripting languages Security Customized tags

IIS, PWS Windows Com No Many Any


Javabeans/EJB Yes

J-script, Java VB-script No yes No yes

• JavaScript – Validates on Client Side – Browser Dependent – Unstable – Interpreted – Server-side JavaScript is dependent on proprietary servers. 11

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

JSP vs Servlets
• Differences – Servlets: “HTML embedded in Java Code”
HTML code inaccessible to Graphics designer But accessible to Programmer.

– JSP: “Java Code embedded in HTML”
HTML code accessible to Graphic Designer Java code accessible to Programmer.

– Jsp allows code update without restarting the server. – Eliminates redundant code.

Comparing servlet and JSP code
1. import java.io.*; 2. import javax.servlet.*; 3. import javax.servlet.http.*; 5. public class HelloWorld extends HttpServlet 6. { 7. public void doGet(HttpServletRequest req, HttpServletResponse res) 8. throws ServletException, IOException 9. { 10. res.setContentType("text/html"); 11. PrintWriter out = res.getWriter(); 12. out.println("<HTML>"); 13. out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>"); 14. out.println("<BODY>"); 15. out.println("<BIG>Hello World</BIG>"); 16. out.println("</BODY></HTML>"); 17. } 18. }

Comparing servlet and JSP code
1. <HTML> 2. <HEAD> <TITLE>Hello World</TITLE></HEAD> 3. <BODY> 4. <h2>Hello World </h1> 5. </BODY> 6. </HTML>

Note: HTML content is also valid JSP content, since JSP is HTML code embedded with java code.

JSP functionality architecture
JSP Page
st que Re

Web Server

Translation by JSP engine Generated Servlet Compilation

Web Client
Re sp



Compiled Servlet Instantiation Servlet is loaded to server

JSP life cycle
• jspInit() • jspDestroy() • _jspService( request, response )
Initialise JSP Invoked only once

Handle Requests: invoked for every request

Invoked by container to cleanup

•Implementation of these methods are generated by the Container and not by JSP authors.

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

Package java.servlet.jsp
Interface Hierarchy

Class Hierarchy

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


Interface JspPage
• It describes the generic interaction that a JSP Page implementation class must satisfy. • Pages that use HTTP protocol are described by HttpJspPage interface.
– public void jspInit() Invoked when the JSP page is initialized. – public void jspDestroy() Invoked before destroying the JSP page.

• Note: The jspInit() and jspDestroy() can be defined by a JSP author, but _jspService() is defined automatically by the JSP processor based on contents of the JSP page.


• Extends JspPage and describes interaction that a JSP Page implementation class must satisfy when using HTTP protocol. • Behaviour is identical to JspPage, except that _jspService method is now expressible in Java type system optimized for HTTP. – void _jspService( HttpServletRequest request, HttpServletResponse response)
• It corresponds to body of the JSP page. • It is defined automatically by the JSP container.

Class JspFactory
•Defines factory methods available to a JSP page at runtime to enable instantiation of implementation-dependent PageContext and JspEngineInfo that support JSP implementation. •JSP Engine, during it's startup instantiates an implementation dependent subclass of this class. •This instance is made globally available by registering it using setDefaultFactory() method. Note: JspFactory objects should not be used by JSP page authors. 23

Class JspFactory
• • • • void setDefaultFactory(JspFactory deflt) JspFactory getDefaultFactory() JspEngineInfo getEngineInfo() PageContext getPageContext( Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needsSession, int buffer, boolean autoflush) – Instantiates an implementation dependent PageContext for the calling Servlet. 24 • abstract void releasePageContext(PageContext pc) static static abstract abstract

Class JspEngineInfo
• Provides information about the current JSP engine (container).
• abstract String getSpecificationVersion() Return version of the JSP specification supported by this JSP engine. May return null, if version details is not known.


Class PageContext
• Provides access to JSP implicit objects and page attributes. • It is an abstract class, and is implemented by container provider. • It is instantiated using static method getPageContext() and is released using releasePageContext() of JspFactory.

Field Summary
• static String APPLICATION Name used to store ServletContext in PageContext name table. • static String CONFIG Name used to store ServletConfig. • static String EXCEPTION Name used for uncaught exception. • static String OUT Name used to store current JspWriter. • static String PAGE Name used to store the Servlet. • static String PAGECONTEXT 27 Name used to store this PageContext.

Field Summary…
• static String REQUEST Name used to store ServletRequest. • static String RESPONSE Name used to store ServletResponse. • static String SESSION Name used to store HttpSession.

• • • •

static static static static

int int int int


Indicates scope of a bean reference.

Method Summary

• The following methods provide convenient access to implicit objects: • abstract JspWriter getOut() Returns current value of the out object (JspWriter). • abstract Object getPage() • abstract ServletRequest getRequest() • abstract ServletResponse getResponse() • abstract ServletConfig getServletConfig() • abstract ServletContext getServletContext() • abstract HttpSession getSession() • abstract Exception getException() 29

Method Summary
• Object findAttribute( String name) Search and return attribute value (or null) in scope sequence of page, request, session and application. • Object getAttribute( String name) Return attribute value of name in page scope. • Enumeration getAttributeNamesInScope(int scope) • abstract int getAttributesScope( String name) • void removeAttribute( String name) Search for attribute in scope order and remove it. • void removeAttribute( String name, int scope) • void setAttribute( String name, Object value) Register attribute in page scope. • void setAttribute( String name, Object v, int scope) 30

Method Summary
• abstract void forward( String relativeUrlPath) Re-directs/forwards current Request and Response to another component. • abstract void include( String relativeUrlPath) Inserts content/output of refered component. • abstract void handlePageException ( Exception e) Redirects exception to the specified error page (if available) or to default handler. • abstract void handlePageException ( Throwable t ) 31

• abstract void initialize(Servlet ser, ServletRequest req, ServletResponse res, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush) Initializes PageContext to be used by a JSP to service an incoming request. • abstract void release() It resets PageContext state, releasing internal references and preparing PageContext for reuse by a later invocation of initialize().

Method Summary

Method Summary
Following methods enable management of JspWriter streams to implement Tag Extensions: • JspWriter popBody() Returns JspWriter saved by the matching pushBody(), and updates value of "out“ attribute in page scope of the PageConxtext. • BodyContent pushBody() Returns a new BodyContent object, and updates the value of "out“ attribute in the page scope attribute namespace of the PageContext. 33

• Provides output stream for JSP's. • It extends java.io.Writer. • A JSPWriter object is available within JSP as implicit object out, which is initialized automatically using methods of PageContext object.
• • • • • • • abstract abstract abstract abstract abstract void void void int int boolean void clearBuffer() close() flush() getBufferSize() getRemaining() isAutoFlush() newLine()

Class JspWriter


Class JspWriter…
void void void void void void void void void print(boolean b) print(char c) print(char[] s) print(double d) print(float f) print(int i) print(long l) print(Object obj) print(String s) void void void void void void void void void void println() println(boolean x) println(char x) println(char[] x) println(double x) println(float x) println(int x) println(long x) println(Object x) println(String x)


Tag convention
• JSP tags usage is similar to those of HTML tags: – They begin and end with angle brackets. • JSP tags fall into 2 basic categories: – Scripting-oriented tags inspired by ASP. – Tags based on XML style.

ASP-like Tags
• They can be recognized by their delimiters. • They start with <% and end with %>. • Additional character may appear after the initial <%, such as !, =, or @, to further specify the meaning of the tag. • Example: <%! double radius = 7.5; %> <%= 2 * Math.PI * radius %> <% if (radius > 10.0) { out.println("Exceeds recommended maximum"); } %> <%@ include file="copyright.html" %> 37

ASP-like Tags…
• NOTE :
– All ASP-scripting like tags are self-contained. – All the information relevant to the tag, and all of the data it will act on, is contained within the individual tags themselves. – None of these scriptingoriented JSP tags have bodies.


XML-like tags
• They start with < and not <% • Tag names have an embedded colon. • They are similar to HTML tags; They can have a "start tag", a "tag body" and an "end tag". • XML syntax is similar to HTML, but adds a few rules to avoid certain problems. – XML tags are case sensitive (<title> and <TITLE> are treated as two different tags). – All attribute values must be quoted (In HTML, quotes are optional). – All XML tags must also have a delimiting tag.

1. <jsp:forward page="admin.jsp"/> 2. <jsp:useBean id="login“
class="UserBean"> <jsp:setProperty name="login“ property="group“ value="admin"/> </jsp:useBean>

Components of a JSP program

• HTML code • Comments • JSP tags • JSP Implicit Objects • Java Beans

Comments in JSP
1. Plain HTML Comments Ex: <!-- hello --> Response: <!-- hello --> 2. HTML Comments containing JSP tags Ex: < !-- value of 10 + 20 is <%= 10 + 20 %> --> Response: <!-- value of 10 + 20 is 30 --> 3. JSP Comment tag Ex: <%-- This is a JSP comment --%> Response: 4. Java Comments Ex: <% /* int x; float f; */ void meth1() { //out.println( “hello output” ); }


JSP tag types
•Declaration tags •For variable and method declaration •Format: <%! Variable declaration; Method declaration; %> •Expression tags •For inserting Java expressions •format: <%= expression %> •Scriptlets •To embed java code blocks •format: <% code block %>


JSP tag types…
•Directives • To specify information that affect the whole JSP program • format: <%@ directive_type directive_attribute %> •Action tags •Used to work with standard objects •format: <jsp:action_name action_attributes /> or <jsp:action_name action_attributes> … </jsp:action_name> 44

General rules
• JSP tags are case sensitive • Tags may have attributes • Attribute values must always appear quoted • White space with in the JSP page is not significant • The \ character can be used as an escape sequence


Sample Program -1
•Using simple expression tag
<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>

Deploying JSP’s on TOMCAT


Deploying JSP’s on J2EE RI Server


Deploying JSP’s on Weblogic


Deploying JSP’s on JRun


Sample Program - 2
•Hello word example <% String name = null; name = request.getParameter(“name”); if ( name == null ) { %> Hello, World <% } else { out.println(“Hello ” + name); } %>


Sample Program - 3
<html> <body> Java Version : <%= System.getProperty( "java.version" ) %> <br> Java Home : <%= System.getProperty( "java.home" ) %> <br> Os Name : <%= System.getProperty( "os.name" ) %> <br> User Name : <%= System.getProperty( "user.name" ) %> <br> User Home : <%= System.getProperty( "user.home" ) %> <br> User Directory : <%= System.getProperty( "user.dir" ) %> <br> </body> </html>

Sample Program - 4
•Simple usage of page directive, scriplet and expression tags.
<%@ 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 - 5
•Using page directive, declaration tag and expression tags together. <%@ 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>


Note about declaration tags
• Declarations in Declaration tag will become instance members. • Variables in Declaration tags will be evaluated only once, during translation of the JSP page. • Its behavior is same as definition of instance variables in a class. • Hence it will not have different functionality for different clients. • Client specific data must not be put in declaration tags, since they are shared. Sessions can be used for the purpose. 55

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

Control statements in JSP
•Using for loops

Sample Program - 7

<html> <body> <%! String items[] = { "bread", "rice", "dal" }; int quantity[] = { 2, 5, 3 }; double cost[] = { 12.50, 19.50, 28.75 }; %> <table align="center" bgcolor="yellow" border ="1" width="75%" > <tr> <td> ITEM </td> <td> QUANTITY </td> <td> PRICE </td> </tr> <% for( int i =0; i < items.length; i++ ) { %> <tr> <td> <%= items[ i ] %> </td> <td> <%= quantity[ i ] %> </td> <td> <%= quantity[ i ] * cost[ i ] %> </td> </tr> <% } %> </table> </body> </html>

Control statements in JSP
•Another example of using for loops

Sample Program - 8

<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 </h<%= i %> > <% } </center> </body> </html> %>


Built-in/Implicit JSP Objects
•Besides objects explicitly created by a developer within JSP scripting elements, the JSP container provides a few internal objects, referred to as implicit objects. •The developer may assume that these objects will be automatically assigned to specific variable names. •They work as a shorthand for certain class/interface instances of Servlet/JSP API. •These Objects are available for ready usage.

JSP Objects description
JSP object Servlet API Object


application javax.servlet.ServletCont Context config exception out

(Execution environment) of javax.servlet.ServletConfi the Servlet. The ServletConfig g for the JSP. java.lang.Throwable The exception that resulted when an error occurred. javax.servlet.jsp.JspWrite An object that r writes into a JSP's output stream.

JSP Objects description…
JSP object Servlet API Object Description pageContext javax.servlet.jsp.PageContext Page context request response session
for the JSP. javax.servlet.HttpServletRequ The client est request. javax.servlet.HttpServletResponse The response to the client. javax.servlet.http.HttpSessio Session n object created for requesting client. javax.servlet.Servlet Refers to current servlet object. 61


•It provides access to data sent within a HTTP Request.
Cookie[] Enumeration String String HttpSession HttpSession
String boolean

request object
getCookies() getHeaderNames() getQueryString() getRemoteUser() getSession() getSession(boolean create)
getRequestedSessionId() isRequestedSessionIdValid()

Enumeration int String boolean boolean StringBuffer String String String

getHeaderNames() getIntHeader(java.lang.String name) getHeader(String name) isRequestedSessionIdFromCookie() isRequestedSessionIdFromURL() getRequestURL() getServletPath() getMethod() getContextPath()


Sample 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>

•It allows setting of response message including html Code, cookies, headers and other information. void void void void void boolean void String String void void addCookie(Cookie cookie) addHeader( String name, String value) addIntHeader( String name, int value) setHeader( String name, String value) setIntHeader( String name, int value) containsHeader( String name) sendRedirect( String location) encodeRedirectURL(String url) encodeURL(String url) setStatus(int sc) setStatus(int sc, String sm)

response object

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>

•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 void Enumeration void void Object String[] void getAttribute( String name) setAttribute( String name, Object value) getAttributeNames() removeAttribute( String name) putValue( String name, Object value) getValue( String name) getValueNames() removeValue( String name)

session object

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

Sample Program - 11
<html> <body> <% java.util.Enumeration attribute_names = session.getAttributeNames(); String attr_name, attr_value; boolean entires_found_flag = false; if( attribute_names != null ) { while( attribute_names.hasMoreElements() ) { entires_found_flag = true; attr_name = (String) attribute_names.nextElement(); attr_value = (String) session.getAttribute( attr_name.trim() ); out.println( "value of the attribute " + attr_name + " is " + attr_value + "<br>" ); } } if( entires_found_flag == false ) { session.setAttribute( "attribute1", "value1" ); session.setAttribute( "attribute2", "value2" ); } %> </body> </html>

Sample Program - 12
<HTML> <BODY> <FORM METHOD=POST ACTION="http://localhost:8080/aaa/B.jsp"> What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20> <P><INPUT TYPE=SUBMIT> A.jsp </FORM> </BODY> </HTML> <% String name = request.getParameter( "username" ); session.setAttribute( "theName", name ); %> <HTML> <BODY> <A HREF="http://localhost:8080/aaa/C.jsp">Continue</A> </BODY></HTML>


<HTML><BODY> Hello, <%= session.getAttribute( "theName" ) %> </BODY></HTML>


application object
•Allows interaction with Servlet container/environment.
Object getAttribute(String name) Enumeration getAttributeNames() void removeAttribute( String name) void setAttribute(java.lang.String name, Object object) String getInitParameter(String name) Enumeration getInitParameterNames() String getServerInfo() int getMajorVersion() int getMinorVersion() String getMimeType( String file ) java.lang.String getRealPath(java.lang.String path) Servlet getServlet(java.lang.String name) Enumeration getServletNames() Enumeration getServlets() void log( Exception exception, String msg) void log( String msg) void log( String message, Throwable throwable) String getServletContextName() RequestDispatcher getRequestDispatcher(java.lang.String path) 70

Sample Program - 12
<HTML> <BODY> <h2>Display the default application settings</h2> <% out.println( application.getServerInfo() + "<br><br>" ); 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>

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

String Enumeration String ServletContext

getInitParameter(String name) getInitParameterNames() getServletName() getServletConext()


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


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


out object
It defines an object for writing to JSP's output stream.
void void int int boolean void void void clearBuffer() flush() getBufferSize() getRemaining() isAutoFlush() newLine() print(...) println(...)


pagecontext object
•It stores information local to a JSP. •Each JSP has its own pageContext object that the server creates when the user accesses the page •It is deallocated when the user leaves the page.
Object void void JspWriter Object ServletRequest ServletResponse ServletConfig ServletContext HttpSession Exception void void findAttribute(String name) removeAttribute(String name) setAttribute(String name, Object attribute) getOut() getPage() getRequest() getResponse() getServletConfig() getServletContext() getSession() getException() forward(String path )  include( String path)     


Sample Code
<html><body> <% Object val = pageContext.findAttribute( pageContext.PAGE ); out.println( val + "<br>" ); val = pageContext.findAttribute( pageContext.APPLICATION ); out.println( val + "<br>" ); val = pageContext.findAttribute( pageContext.CONFIG ); out.println( val + "<br>" ); val = pageContext.findAttribute( pageContext.EXCEPTION ); out.println( val + "<br>" ); val = pageContext.findAttribute( pageContext.OUT ); out.println( val + "<br>" ); val = pageContext.findAttribute( pageContext.PAGECONTEXT ); out.println( val + "<br>" ); %> </body></html>


JSP Standard Action Tags
(XML format)

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

JSP Action tags (Contd)
• Standard action tags start with the namespace prefix jsp followed by a colon and then by tag name. • Ex: <jsp:param> • Actions may have attributes and tag bodies.

Handling of Actions
•JSP translators treat action tags as tokens that must be replaced with Java code. •Code for actions are defined in a tag library. •The translator simply replaces action tags with output of the code that is referenced by the action.

Handling of Actions…
• Ex: The tag
<jsp:useBean id=“test” class=“one.two.Tester”>

will be replaced with
Object test = (one.two.Tester) java.beans.Beans.instantiate( this.getClass().getClassLoader(), “one.two.Tester” );


Action tags
• Following actions tags are available: • <jsp:useBean> • • • • • • <jsp:getProperty> <jsp:setProperty> <jsp:param> <jsp:forward> <jsp:include> <jsp:plugin>

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

Attributes in useBean tag
id scope class type

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

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

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

Attributes in setProperty tag
• The name and property attributes are mandatory. • param and value attributes are mutually exclusive. • If param and value are not used, the tag attempts to use value of the request parameter with same name.


getProperty 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.

Bean access code 1 (bean)
package test; public class StudentBean { private int id; private String name; public StudentBean() { id = -1; name = "---"; } public int getId() public void setId( int student_id ) public String getName() public void setName( String n ) }


{ { { {

return id; id = student_id; } return name; } name = n;

} }

Bean access code 1 (JSP)
<jsp:useBean id="stBean" class="test.StudentBean" scope="page" /> <html> <body> Details Before changing the bean <br> Student id : <jsp:getProperty name="stBean" property="id" /> <br> Student name : <jsp:getProperty name="stBean" property="name" /> <br> <br> <br> <jsp:setProperty name="stBean" property="id" value="101" /> <jsp:setProperty name="stBean" property="name" value="step_student" /> Details After changing the bean <br> Student id : <jsp:getProperty name="stBean" property="id" /> <br> Student name : <jsp:getProperty name="stBean" property="name" /> </body> </html>

Beans and Form processing
package test2; public class UserData { String username; String email; int age; public void setUsername( String value ){ public void setEmail( String value ){ public void setAge( int value ){ username = value; email = value; } } }


age = value;

public String getUsername() { return username; } public String getEmail() { return email; } public int getAge() { return age; } }


Beans and Form processing
<HTML> <BODY> <FORM METHOD=POST ACTION="beantest.jsp"> What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR> What's your e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR> What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4> test.html <P><INPUT TYPE=SUBMIT> </FORM></BODY> </HTML> <jsp:useBean id="user" class="test2.UserData" scope="session"/> <jsp:setProperty name="user" property="*"/> <HTML> <BODY> <A HREF=result.jsp>Continue</A>


<jsp:useBean id="user" class="test2.UserData" scope="session"/> <HTML> <BODY> The following data were received by the client <BR> Name: <%= user.getUsername() %><BR> Email: <%= user.getEmail() %><BR> Age: <%= user.getAge() %><BR> </BODY> </HTML>



Another Example
package test3; public class User { private String id; private String surname; public void setId( String id ){ this.id = id; } public String getId(){ return id; } public void setSurname( String surname ) { this.surname = surname; } public String getSurname( ){ return surname; } }


Another Example
<jsp:useBean id="userA" class="test3.User" /> <jsp:setProperty name="userA" property="surname" value="Smith" /> <jsp:setProperty name="userA" property="id" value="<%= 32 + 45 + "45" %>" /> Your data are as follows : <br> ID : <jsp:getProperty name="userA" property="id" /> <br> SURNAME : <jsp:getProperty name="userA" property="surname" />


include action tag
• It allows embedding of another page within the current jsp. • Included components must be valid JSP pages or servlets. • Note: Included file is not allowed to modify response headers, nor to set cookies in the response. • Syntax: <jsp:include page->file (Mandatory) flush->true/false (Optional)


How include action works
1. Original JSP file stops processing and passes the request to included file. 2. The included file generates its response. 3. Response of the included file is returned to the calling JSP, which proceeds with its processing and generates the final response.

Sample Code
<HTML> <HEAD><TITLE>Example Of The include Action</TITLE></HEAD> <BODY> Include the First File <jsp:include page="test1.jsp" /> <BR> Include the Second File: <jsp:include page="test2.jsp" /> </BODY> </HTML>


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


How forward action works
• Original JSP file stops processing and passes the request to forwarded component. • Forwarded component generates the final response. • Note:
– Execution never returns to the calling page. – Only one effective forward action is valid in a JSP document, later forward actions are ignored.

Sample 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>

param action tag
• It is used in conjunction (as a sub-tag) with include or forward action. • It is used to pass parameters to the resource being included/forwarded. • In the included/forwarded resource these parameters can be accessed using getParameter() method.
• Syntax: <jsp:include …..> <jsp:param name->name value->value > . . </jsp:include>


plugin action tag
• It is used to embed objects for execution on client • It is similar to <applet> tag • Syntax: <jsp:plugin type->applet/bean code->class name codebase->codebase width->width height->height align->alignment archive->archive list nspluginurl->url iepluginurl->url /> 102

• Directives give instructions to the JSP container to be interpreted at translation time. The general Syntax: <%@ directivename attribute=“value” attribute=”value”%> • There are 3 directives – The page directive – The include directive – The taglib directive



Page Directive
Defines attributes applicable to the entire JSP page. – <%@ page atribute_name=attribute_value %> – Possible attributes • language=“java” • extends=“package.class” • import=“package.*, package.class,…” • session=“true” • buffer=“8kb” • autoFlush=“true” • isThreadSafe=“true” • info=“text” • errorPage=“relativeURL” • isErrorPage=“false” • contentType=“mimeType” • pageEncoding=encoding
Note: The extends attribute is recommended not to be used.

Page Directive - Details
Attribute info language Value Text string Scripting lang Default None “java” “text’html” None None “true” “true” “true” None “false” Example info=“Registration form” language=“java” contentType=“text/java” extends=“com.gui.MyGUI” import=“java.net.URL” multiple imports separated by “,” session=“true” autoFlush=“false” isTheadSafe=“true” errorPage=“msg/failed.jsp” isErrorPage=“false”

contentType MIME type, extends import session buffer autoFlush errorPage Class name Packages(s) Boolean flag Size or none Boolean flag Local URL

Server specific buffer=“12kb” buffer=“false”

isThreadSafeBoolean flag isErrorPage Boolean flag

Sample code
<html> <body> <%@page info="jaa re bakra" %> <%= getServletInfo() %> </body> </html> <html> <body> <!-<%= "hello" %> <%@page info="haal chaal kya khabar" %> --> <%= getServletInfo() %> </body> </html>

Handling Exceptions using errorPage
<html> <body> well come to error test <%@page errorPage="error.jsp" %> <% %> </body> </html> <html> <body> Hai how r u <br/> <%@page isErrorPage="true" %> <br> <% out.println ( "error " + exception ); %> <br/> <br/> Hello am fine </body> </html> int x = 10, y = 0; out.println( x/y ); out.println( "all is well" ); error_test.jsp



include Directive
• Used to include a specified file's content into this page at translation time. • If the included file content changes, it is not reflected until server is restarted or until the main JSP file changes. • Only static pages are recommended to be included. • Syntax: <%@ include file=“file_name" %>

Sample Code
<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>



include directive vs include action directive
Included at JSP translation time. Inclusion is static in nature. Recommended for static/template data. Cannot pass parameters.

Included at JSP request time. Inclusion is dynamic. Web component usage recommended. Can pass parameters using


Tag libraries <taglib> directive

Tag Libraries
• JSP Tags can be of two types: – Predefined tags: They have jsp: as prefix. Ex: jsp:include. – Custom tags: They are external, user defined tag library. • The ability to define custom tags were made possible in JSP 1.1

Tag Library
• It is a collection of custom actions/tags, included in a JSP page. • Defining custom tags involve: – Development of tag handlers for the tag. – Declaration of tag in tag library descriptor. • A tag library defines a set of related, custom tags and links them to objects (tag handlers) that implements functionality for the tags. • JSP container uses TLD to interpret/handle taglib directives inside JSP documents. 113

Advantages of Tag Library
• Custom tags allow a convenient way to provide extension of JSP functionality. • Role segregation: • Tag libraries are created by Java developers which will be used by Web application designers. Hence division of labor between library developers and library users. • Enhanced productivity by hiding implementation details and encapsulating redundant code. 114

taglib Directive
•It allows us to access user-defined/custom tags in a JSP. •Syntax: <%@ taglib uri=“tld uri” prefix=“unique name” %> •Both attributes are mandatory. •More than one taglib directive can be used in the same JSP.

Attribute uri
• TLD files are stored in WEB-INF directory of WAR or in a subdirectory of WEB-INF. • You can reference a TLD directly or indirectly. Ex: – Direct reference • <%@ taglib uri="/WEB-INF/one.tld" prefix="tt" %> – Indirect reference (uses a short logical name) • <%@ taglib uri="/aab" prefix="tt" %> • Logical name is mapped to absolute location in deployment descriptor using following entries: <taglib> <taglib-uri>/aab</taglib-uri> 116 <taglib-location>/web-inf/one.tld</taglib-location>

Custom tags and TLD
•Custom tags are accessed in the JSP document using prefix name followed by the tag name. •Prefix names uniquely identify tags in spite of tag namespace reuse in different tag libraries. •A prefix can not be java, javax, jsp, jspx, servlet, sun and sunw.

Custom tags and TLD
• Container takes necessary action when custom tag is encountered. • When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on the respective tag handler. • The web container then invokes those operations when the JSP page’s servlet is executed.

TLD format
<?xml version="1.0"> <!DOCTYPE taglib SYSTEM "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> <taglib> <tlib-version> version (M) </tlib-version> <jsp-version> compatible jsp version (O) </jsp-version> <short-name> document name (M) </short-name> <uri> Unique string (O) </uri> <display-name>name in visual tools (O) </display-name> <small-icon>small icon in visual tools (O) </small-icon> <large-icon>large icon in visual tools (O) </large-icon> <description> Description (O) </description> <tag>------------ </tag> <tag>------------ </tag> 119 </taglib>

TLD 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> 120

TLD Tag Description
General Description elements/tags

<tlibversion> <jspversion> <shortname> <uri> <tag>

Version number of library. (Must) Compliant JSP version. Simple default name. Preferred prefix value in taglib directive. (Must) Unique uri of the TLD document. Contains elements describing the tag.

<description> Description/comments about TLD.

TLD Tag Description
Tags within the <tag> tag.
Tag <name> <tag-class> <tei-class> <bodycontent> Description Name of the tag Full class name of tag handler. Subclass of TagExtraInfo. Specifies whether tag can have content. Can be one of the following: tagdependent :- contains non-jsp code. JSP :- body contains JSP code. empty :- no body for this tag. <variable> Scripting variable information. <attribute> Defines attributes for the tag. 122

TLD Tag Description
Tags within the <attribute> tag.

<name> <required>

Defines attribute name. Specifies whether attribute is optional or not. (default – false) Values - true/false/yes/no Specifies whether the attribute value can be run time expression or static. Values - true/false/yes/no Specifies fully qualified data type. (Static values are always of type String). 123



TLD Tag Description
Tags within the <variable> tag. Tag Description
<name-given> <name-fromattribute> The variable name as a constant. Attribute name whose translation-time value will give name of the variable. One among name-given or name-from-attribute is mandatory. <variable-class> Fully qualified class name (type) of the variable. java.lang.String is default. <declare> Whether the variable refers to a new object. True is default. <scope> Scope of variable. NESTED is default. 124

TLD Tag Description
Possible values for <scope> tag within <variable> tag


Between start tag and end tag


In doInitBody and doAfterBody if tag handler implements BodyTag; otherwise, in doStartTag. doInitBody, AT_BEGIN From start tag until end of the page doAfterBody & doEndTag id tag handler implements BodyTag; otherwise, in After end tag until end doStartTag & In doEndTag. AT_END doEndTag. of the page

Code – 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>


Code – Java class
package test; import java.util.Date; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class DateClass extends TagSupport { public int doEndTag() throws JspException { try{ Date dt = new Date(); String dt_str = "" + dt; pageContext.getOut().write( dt_str ); }catch( Exception e) return EVAL_PAGE; } }


System.out.println( e );


Code – Jsp file
<%@ page language="java" %> <%@ taglib uri="CurrentDate.tld" prefix="date" %> <html> <body> <h1> The date & time now is : <date:today /> </h1> </body> </html>


Custom Tag types

Simple Tags
• A simple tag contains no body and no attributes. • Ex: <prefix_name:tag_name /> • It would have the following entry in the respective TLD: <body-content>empty</body-content>

Tags With Attributes
• A custom tag can have attributes listed in start tag having syntax attr="value". • Attributes customize behavior of a custom tag just as parameters customize the behavior of a method. • Attribute value can be a String constant or a runtime expression. Ex: 4.<prefix_name:tag_name attr=“val" /> 5.<prefix_name:tag_name attr1="<%=bookDB.getBooks()%>" attrib2="val" />

Tags with Bodies
• A custom tag can contain custom and core tags, scripting elements, HTML text, and tagdependent body content between the start and end tag. • Ex: <prefix_name:tag_name attrib_name="val" /> <% cart.clear(); %> <font color="#ff0000" size="+2"><strong> You just cleared your shopping cart! </strong><br>&nbsp;<br></font> </prefix_name:tag_name> 132

Tags That Define Scripting Variables
• A custom tag can define a variable that can be used in scripts within a page.
1)<tt:lookup id="tx" type="UserTransaction" name="java:comp/UserTransaction" /> <% tx.begin(); %> 2) <tt:define id="book" name="bookDB" /> <jsp:getProperty name="book" property="title">

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

Tag Handlers
• It is a Java class that implements behavior of a custom tag. • It is invoked by Web container to evaluate a custom tag during execution of JSP page that references the tag. • They must implement either Tag or BodyTag interface, preferably via TagSupport and BodyTagSupport classes respectively. • Tag handlers will be referenced in TLD files. 135

Tag Handlers…
• Tag handlers have access to an API that allows it to communicate with the JSP page. • Entry point to the API is PageContext, through which a tag handler can retrieve all implicit objects accessible from a JSP page.

Package javax.servlet.jsp.tag ext

Interface Hierarchy


•It defines a handler for simple tags which does not manipulate tag body. •It specifies a framework (protocol) for interaction between a Tag handler and JSP page implementation class. • i.e. it defines the life cycle methods to be invoked at start and end tag. •It specifies accessor methods for pageContext and parent properties.


Tag – Method summary
void void int int Tag void setPageContext(PageContext pc) setParent(Tag t) doStartTag() doEndTag() getParent() release()

• JSP page implementation object invokes setPageContext and setParent, in that order, before invoking doStartTag() or doEndTag().


Tag - Field Summary
• static int SKIP_BODY Skip body evaluation. • static int EVAL_BODY_INCLUDE Evaluate the tag body. • static int SKIP_PAGE Skip the rest of the page. • static int EVAL_PAGE Continue evaluating the page.

Tag - Field usage
•If the TLD file indicates that the action tag must be empty, then doStartTag() must return SKIP_BODY. •Otherwise, the doStartTag() method may 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. 142

Sample code
A simple tag for example <abc:simple /> would be implemented by the following tag handler:
public SimpleTag extends TagSupport { public int doStartTag() throws JspException { try { pageContext.getOut().print("Hello."); } catch (Exception ex) { pageContext.getOut().print("SimpleTag: " + ex.getMessage()); } return SKIP_BODY; } public int doEndTag() { return EVAL_PAGE;

} 143

• It extends Tag by defining one additional method ( doAfterBody() ) that processes tag body. • The doAfterBody() is invoked after body evaluation iff doStartTag() returns EVAL_BODY_INCLUDE. • If it returns EVAL_BODY_AGAIN, then the body will be reevaluated. • If it returns SKIP_BODY, then the body reevaluation will be skipped and doEndTag() is invoked. 144

IterationTag Members
Field Summary • static int EVAL_BODY_AGAIN Request reevaluation of body content. Method Summary • int doAfterBody() Process body content.


• It extends IterationTag and defines additional methods that let a tag handler to manipulate body content by providing buffering. • While implementing BodyTag, the doStartTag() can return SKIP_BODY, EVAL_BODY_INCLUDE or EVAL_BODY_BUFFERED.

•If EVAL_BODY_BUFFERED is returned, then a BodyContent object will be created by the container to encapsulate the body. •The container creates BodyContent object by calling pushBody() of the current pageContext. •The container returns this object to JSP by calling popBody() of the PageContext.

Field Summary
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.

Method Summary
void setBodyContent(BodyContent b)
Sets the bodyContent. It will be invoked by container.

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

Both methods will be invoked only if doStartTag() 149 returns EVAL_BODY_BUFFERED

BodyTag - Field usage
•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. 150

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

Interface TryCatchFinally
•It provides optional support for tag handlers implementing Tag, IterationTag or BodyTag. Method Summary void doCatch( Throwable t ) Will be invoked if a Throwable occurs while evaluating BODY. void doFinally() Will be invoked in all cases after doEndTag() for any class implementing Tag, IterationTag or BodyTag. 152

Class Hierarchy


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

Field Summary
• protected String • protected PageContext Fields inherited from Tag • EVAL_BODY_INCLUDE • EVAL_PAGE • SKIP_BODY • SKIP_PAGE Fields inherited from IterationTag • EVAL_BODY_AGAIN id pageContext


Method Summary
• int doStartTag() Default processing of start tag. • int doEndTag() Default processing of end tag. • int doAfterBody() Default processing for a body. • static Tag findAncestorWithClass(Tag from, Class klass) Find instance of given type closest to given tag. • String getId() The value of the id attribute of this tag; or null. • void setId(String id) Set the id attribute for this tag.


Method Summary…
• Tag getParent() The Tag instance most closely enclosing this tag instance. • void setParent(Tag t) Set the nesting tag of this tag. • Object getValue(String k) Get a the value associated with a key. • Enumeration getValues() • void setValue(String k, Object o) • void removeValue(String k) • void setPageContext(PageContext pageContext) • void release()

Class BodyTagSupport
• A base class for defining tag handlers implementing BodyTag. • It implements BodyTag, IterationTag, Serializable and Tag interfaces • It adds additional methods including getter methods for bodyContent property and methods to get the previous out (JspWriter).


Field Summary
• protected BodyContent bodyContent Fields inherited from TagSupport • Id • pageContext Fields inherited from interface Tag • EVAL_BODY_INCLUDE • EVAL_PAGE • SKIP_BODY, SKIP_PAGE Fields inherited from interface IterationTag • EVAL_BODY_AGAIN Fields inherited from interface BodyTag • EVAL_BODY_BUFFERED • EVAL_BODY_TAG (Deprecated)


Method Summary
• int doStartTag() Default processing of start tag. • void setBodyContent(BodyContent b) Prepare for evaluation of the body; store bodyContent. • void doInitBody() Prepare for body evaluation just before first body evaluation. • int doAfterBody() After body evaluation. • int doEndTag() 160 Default processing of the end tag.

Method Summary…
• BodyContent getBodyContent() Get current bodyContent. • JspWriter getPreviousOut() Get the out (JspWriter). • void release()


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

Method Summary
• protected BodyContent(JspWriter e) • void clearBody() • abstract java.io.Reader getReader() Return value of this BodyContent as a Reader. • abstract String getString() Return value of the BodyContent as a String. • abstract void writeOut(java.io.Writer out) Write contents of this BodyContent into a Writer.

Class TagExtraInfo
• Optional class specified in the TLD to describe additional translation-time information not described in the TLD. • TagExtraInfo class must be mentioned in TLD file. • This class can be used:
– to indicate that the tag defines scripting variables – to perform translation-time validation of the tag attributes.


Method Summary
• TagInfo getTagInfo() Get the TagInfo for this class. • VariableInfo[] getVariableInfo(TagData data) information on scripting variables defined by the tag associated with this TagExtraInfo instance. • boolean isValid(TagData data) Translation-time validation of the attributes. • void setTagInfo(TagInfo tagInfo) Set the TagInfo for this class.

Class TagInfo
• Tag information for a tag in a Tag Library; This class is instantiated from the TLD and is available only at translation time.


Field Summary
• static String BODY_CONTENT_EMPTY static constant for getBodyContent() when it is empty • static String BODY_CONTENT_JSP static constant for getBodyContent() when it is JSP • static String BODY_CONTENT_TAG_DEPENDENT static constant for getBodyContent() when it is Tag dependent

Method Summary
• String getTagName() • String getTagClassName() • TagExtraInfo getTagExtraInfo() The instance (if any) for extra tag information • String getBodyContent() • String getDisplayName() • String getSmallIcon() • String getLargeIcon() • String getInfoString()

Method Summary…
• TagAttributeInfo[] getAttributes() • TagVariableInfo[] getTagVariableInfos() • TagLibraryInfo getTagLibrary() • boolean isValid(TagData data) Translation-time validation of attributes.


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


Member summary
Field Summary • static int AT_BEGIN • static int AT_END • static int NESTED Method Summary • String getVarName() • String getClassName() • boolean getDeclare() • int getScope()


Class TagVariableInfo
• Provides scripting variable information for a tag in a Tag Library. • This class is instantiated from the TLD and is available only at translation time. • This information is only available in JSP1.2


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


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


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


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


Field Summary
• protected String tlibversion • protected String jspversion • protected String shortname • protected String uri • protected String info • protected TagInfo[] tags

Method Summary
• String getRequiredVersion() • String getShortName() • String getURI() • String getInfoString() • TagInfo getTag(java.lang.String shortname) • TagInfo[] getTags()

Class PageData
•Provides information about the JSP page during translation time. •Information corresponds to XML view of JSP page contents. •It is instantiated and used by the container. Method Summary abstract InputStream getInputStream() Returns input stream on the XML view (include directives will be expanded) of a JSP page. 179

Class TagAttributeInfo
•Provides information about Tag attributes, available at translation time. •It is instantiated using information in the TLD file. Field Summary static String ID "id" is wired in to be ID. Constructor Summary TagAttributeInfo( String name, boolean required, String type, boolean reqTime)


Method Summary
boolean canBeRequestTime() Determines whether this attribute can hold a request-time 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.

Class TagData
Provides information about attribute/value for a tag instance at translation-time only. •It is only used as an argument to isValid() and getVariableInfo() of TagExtraInfo, which are invoked at translation time.

Object getAttribute(String attName) Enumeration getAttributes() String getAttributeString(String attName) void setAttribute( String attName, Object value) 182

Writing Tag Handlers


Simple tags
• Handler for simple tag must implement doStartTag and doEndTag methods of Tag interface. • Method doStartTag is invoked when the start tag is encountered. • Method doStartTag must return SKIP_BODY since simple tags have no body. • Method doEndTag is invoked when the end tag is encountered. • Method doEndTag needs to return EVAL_PAGE if the rest of the page needs to be evaluated; otherwise, it should return SKIP_PAGE. 184

Simple tag - Example
A simple tag <tt:simple /> would be implemented by the following tag handler: public SimpleTag extends TagSupport { public int doStartTag() throws JspException { try { pageContext.getOut().print("Hello."); } catch (Exception ex) { throw new JspTagException("SimpleTag: " + ex.getMessage()); } return SKIP_BODY; } public int doEndTag() { return EVAL_PAGE; } }


Tags with Attributes
• In this case for each attribute, the Tag Handler must define a property as well as get and set methods that conform to JavaBeans architecture conventions. • Ex: Tag handler for following tag in JSP, <prefix:tag_name parameter="Clear"> contains the following declaration and methods: private String parameter = null; public String getParameter() { return parameter; } public void setParameter(String parameter) { this.parameter = parameter; } 186

Attribute Validation
• The tag library documentation should describe valid values for tag attributes. • During JSP translation, container enforces constraints contained in TLD for each attribute. • Attributes passed to a tag can also be validated during translation using isValid method of a class derived from TagExtraInfo. • Method isValid is passed a TagData object, which contains information about each attribute.

Attribute Validation using TagExtraInfo
• The tag <tt:twa attr1="value1"/> has the following TLD attribute element: <attribute> <name>attr1</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> • This declaration indicates that the value of attr1 can be determined at runtime. • The following isValid method checks that the value of attr1 is a valid Boolean value.

Attribute Validation…
public class TEI extends TagExtraInfo { public boolean isValid(Tagdata data) { Object o = data.getAttribute("attr1"); if (o != null ) { if ( ((String)o).toLowerCase().equals("true") ) return true; else return false; } else return false; } 189 }

Tags with Bodies
• A tag handler for a tag with body is implemented differently depending on whether the tag handler needs to interact with the body or not. • A tag is said to interact with body content if the tag handler reads/modifies body content.


Tag Handler Does Not Interact with Body
•If tag handler does not need to interact with body, it should implement Tag interface or extend TagSupport. •If tag body needs to be evaluated, doStartTag method must return EVAL_BODY_INCLUDE; otherwise it should return SKIP_BODY. •If a tag handler needs to iteratively evaluate the body, it should implement IterationTag or extend TagSupport. •It should return EVAL_BODY_AGAIN from the doStartTag and doAfterBody methods if the body needs to be evaluated again. 191

Tag Handler Interacts with Body
• If tag handler needs to interact with body, it must implement BodyTag or extend BodyTagSupport. • Such handlers implement doInitBody and doAfterBody. • These methods have access to BodyContent object, which provides several methods to read and write body. • A tag handler can use BodyContent's getString or getReader methods to extract body information and writeOut(out) to write the body contents to out stream. • The parameter supplied to writeOut method is obtained using tag handler's getPreviousOut method. • This method ensures that a tag handler's results192 are

Tag Handler Interacts with Body…
doInitBody Method • It is called before body content is evaluated and hence is generally used to perform any initialization that depends on body content. doAfterBody Method • It is called after the body content is evaluated. • Like doStartTag method, doAfterBody must return an indication of whether to continue evaluating body. • Thus, if body should be evaluated again, doAfterBody should return EVAL_BODY_BUFFERED; otherwise, it should return SKIP_BODY. release Method • A tag handler should release any private resources in the release method. 193

Tag Handler Interacts with Body…
• The tag handler below reads body content (which contains a SQL query) and executes the query. Since body does not need to be reevaluated, doAfterBody returns SKIP_BODY. public class QueryTag extends BodyTagSupport { public int doAfterBody() throws JspTagException { BodyContent bc = getBodyContent(); String query = bc.getString(); try { Statement stmt = connection.createStatement(); ResultSet result = stmt.executeQuery(query); …….. } catch (SQLException e) { throw new JspTagException("QueryTag: " + e); } return SKIP_BODY; } 194 }

Tag Handler Interacts with Body…
body-content Element • For tags that have a body, body content type must be specified using body-content element: <body-content>JSP/tagdependent</body-content> • Body content containing custom/core tags, scripting elements, and HTML text is categorized as JSP. • All other types of body content--for example--SQL statements would be labeled tagdependent. Note: Value of body-content element does not affect body interpretation by tag handler; It is only intended to be used by an authoring tool for body content. 195

Thank You

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->