Anda di halaman 1dari 57

Java Server Pages

The goal of the Java Server Pages (JSP) specification is to simplicity the creation and management of dynamic web pages, by separating contents and presentation. JSPs are basically that combine standard HTML (or XML) and new scripting tags. The presentation is using HTML while the new tags specify the dynamic contents. This is not to say that JSPs must contain HTML. A JSP page might be composed of only java code, or of custom tags that refer to externally compiled classes. JSP is not a product, but like other Java APIs, a specification provide by the sun Microsystems for vendors to implement. The JSP specification builds on the functionality provided by the Servlet Specification. JSPs get translated into Java Servlets the first time they are invoked by a client. From then on, as long as the JSP source for the page is not modified, this compiled servlet process any browser request for that JSP page.

Servlet v/s JSP


Servlets execute on the server and intercept browser requests, acting as a sort of middle Layer between Clients and other applications. In doing so, Servlets tend to mix the dynamic content into the static part to generate HTML. JSPs on the other hand, separate static and dynamic content separating presentation and logic in a web application. Whereas servlets force you to mix the code with the static content, JSPs can use beans with a specified scope to separate the code out, or tag extensions.

ASP v/s JSP


The main competing technology for JSPs is Active Server Page (ASP) , from Microsoft. The technologies are quite similar in the way they support the creation of Dynamic pages, using HTML templates, scripting code and components for business logic. The following table provides a comparison:

JSP
Platform Scripting Language Components Code Interpretation All major Web Platforms Java JSP tags, JavaBeans, or EJB Once

ASP
Microsoft only JScript or VBScript COM / DCOM Each Instance

JSP Scores over the ASP in that: JSPs are interpreted only once, to Java byte code and re-interpreted only when the file is modified. JSPs run on all the main web servers. JSPs provide better facilities for separation of page code and template data by mean of Java beans, EJBs and custom tag libraries.

Author - Sumit Agarwal (sagarwal10@sapient.com)

JSP Life Cycle


When the server receives a request for a JSP, the web server recognizes the JSP file extension in the URL requested by the browser, indicating that the requested resources is a JSP, and therefore must be handled by the JSP engine (Web Container). The JSP page is translated into a Java file, which is then compiled into a servlet. This transaction and compilation phase occurs only when the JSP file is first called, or when it subsequently changes. You will notice a slight delay the first time that a JavaServer Page is run because of this conversion process.

Generated Implementation Class and JSP Life Cycle


The Servlet class generated at the end of the translation process must extend a super class that is either A JSP container specific implementation class that implements the javax.servlet.jsp.JspPage interface and provides some basic page specific behavior. Since most JSP pages use HTTP, their implementation must actually implement the javax.servlet.jsp.HttpJspPage interface, which is a sub interface of javax.servlet.jsp.JspPage interface. The javax.servlet.jsp.JspPage interface contains two methods public void jspInit( ) This is invoked when the JSP is initialized. This is similar to init( ) method in servlets. Page authors are free to provide initialization of the JSP by implementing this method in their JSP. public void jspDestroy( ) This is invoked when the JSP is about to be destroyed by the container. This is similar to the destroy( ) method in servlets. Page authors are free to provide cleanup of the JSP by implementing this method in their JSPs. public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException This method corresponds to the body of the JSP Page and is used for the threaded request processing, just like the service( ) method in servlets. The Implementation for this method is generated by the JSP container and should never be provided by the page authors. The order in which these three methods work together in a JSP page is given below: 1. jspInit( ) 2. _jspService( ) Every time a request comes to JSP, the container generated _jspService( ) method is invoked, the request is processed and the JSP generates the appropriate response. This response is taken by the container and passed back to the client. 3. jspDestroy( ) Note that in most cases. The jspInit( ) and jspDestroy( ) methods do not need to be provided by the JSP authors and can be omitted.

The javax.servlet.jsp.HttpJspPage interface contains a single method:

Author - Sumit Agarwal (sagarwal10@sapient.com)

************************Simple JSP Page ********************************************* <%@page info="Hello JSP Page" isErrorPage="true" import="java.util.Date"%> <html> <body> The Current Time is <%= new Date().toString()%> <br> <% out.println("Hello " + request.getParameter("name")); %> <br> <% out.println("i = " + i); %> <br> <% for(int i=0; i<3; i++) { out.println("Hello to Client: " + i + "&nbsp" + "<br>"); System.out.println("This goes to the System.out stream: " +i); } %> The Current Time is <%= new Date()%> <%! static int i=10; %> <br> <%= this.getServletInfo() %> </html> </body> ************************ package org.apache.jsp; import import import import

Translated JSP Code **********************************************

javax.servlet.*; javax.servlet.http.*; javax.servlet.jsp.*; java.util.Date;

public final class test1_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { public String getServletInfo() { return "Hello JSP Page"; } static int i=10; private static java.util.Vector _jspx_dependants; public java.util.List getDependants() { return _jspx_dependants; } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { JspFactory _jspxFactory = null; PageContext pageContext = null; HttpSession session = null; Throwable exception = org.apache.jasper.runtime.JspRuntimeLibrary.getThrowable(request); ServletContext application = null; ServletConfig config = null; JspWriter out = null;

Author - Sumit Agarwal (sagarwal10@sapient.com)

Object page = this; JspWriter _jspx_out = null; try { _jspxFactory = JspFactory.getDefaultFactory(); response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\r\n<html>\r\n<body>\r\nThe Current Time is "); out.print( new Date().toString()); out.write("\r\n<br>\r\n"); out.println("Hello " + request.getParameter("name")); out.write("\r\n<br>\r\n"); out.println("i = " + i); out.write("\r\n<br>\r\n"); for(int i=0; i<3; i++) { out.println("Hello to Client: " + i + "&nbsp" + "<br>"); System.out.println("This goes to the System.out stream: " +i); } out.write(" \r\nThe Current Time is "); out.print( new Date()); out.write('\r'); out.write('\n'); out.write("\r\n<br>\r\n"); out.print( this.getServletInfo() ); out.write("\r\n</html>\r\n</body>\r\n "); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (pageContext != null) pageContext.handlePageException(t); } } finally { if (_jspxFactory != null) _jspxFactory.releasePageContext(pageContext); } } }

Author - Sumit Agarwal (sagarwal10@sapient.com)

The Nuts and Bolts (Elements/Constructs)


The Structure of a JSP Page is a cross between a servlet and an HTML page.

JSP tags fall into three categories:


Directives
These affect the overall structure of the servlet that results from translation, but produce no output themselves.

Scripting Elements These let us insert java code into the JSP page and hence into the resulting servlet. Actions These are special tags available to affect the runtime behavior of the JSP Page. JSP supplies some standard tags, such as <jsp:useBean>. We can also write our own tags. The custom actions are usually referred to as tag extensions or custom tags. Note: JSP tags are case-sensitive. So Jsp Page will consist of above elements and Template Text (HTML).

JSP Directives
JSP directives configure the code generation that the container will perform in creating a servlet. They are used to set global values such as class declarations, methods to be implemented, output content type, and so on, and do not produce any output to the client. Directives have scope for the entire JSP Page in other wards, a directive affect the whole JSP page, but only that page. Directives begin with <%@ and end with %>, and the general syntax is: <%@ directivename attribute = value attribute = value %> There are three main directives that can be used in a JSP Page: o The page directive o The include directive o The taglib directive

The page Directive


The page directive is used to define and manipulate a number of important attribute that affect the whole JSP page. A page can contain any number of page directives, in any order, anywhere in the JSP page. They are all assimilated during translation and applied together to the page. However, there can be only one occurrence of any attribute-value pair defined by the page directives in a given JSP. An exception to this rule is the import attribute; there can be multiple imports. By convention, page directives appear at the start of the JSP Page. The general syntax of the page directive is <%@ page ATTRIBUTES %>

Author - Sumit Agarwal (sagarwal10@sapient.com)

Where the valid attributes are the following name-value pairs. Attribute language extends Description Defines the scripting language to be used. This attribute exists in case future JSP containers support multiple languages. The value is a fully qualified class name of the superclass that The generated class, into which this JSP page is translated, must extend. Comma separated list of packages or classes, with the same meaning as import statements in Java classes. Specifies whether the page participates in an HTTP session. When true the implicit object named session, which refer to the javax.servlet.http.HttpSession, is available and can be used to access the current/new session for the page. If false, the page does not participate in a session and the implicit session object is unavailable. Default value Java Omitted by default Omitted by default true

import session

buffer

Specifies the buffering model for the output stream to the client. Implementation If the value is none, no buffering occurs and all output is written directly through to the ServletResponse by a PrintWriter. If a buffer size is specified (for example, 24kb), output is buffered with a buffer size not less than that value. -dependent; at least 8kb

autoFlush

If true, the output buffer to the client is flushed automatically true When it is full. If false, a runtime exception is raised to indicate a buffer overflow.

Author - Sumit Agarwal (sagarwal10@sapient.com)

Attribute isThreadSafe

Description Define the level of thread safety implemented in the page. If the value is true the JSP engine may send multiple client requests to the page at the same time . If the value is false then the JSP container queues up client requests sent to the page for processing, and processes then one at a time, in the order in which they were received. This is the same as implementing the javax.servlet.SingleThreadModel interface in a servlet.

Default value true

info

Define an informative string that can subsequently be obtained from the page implementation of the Servlet.getServletInfo() method. Defines a URL to another JSP page within the current web application, which is invoked if a checked or unchecked exception is thrown. The page implementation catches the instance of the Throwable object and passes it to the error page processing. The error page mechanism is very useful, and avoids the need for developers to write code to catch unrecoverable exceptions in their JSP pages. See the isErrorPage attribute below. Indicates if the current JSP page is intended to be another JSP pages error page. If true, then the implicit variable exception is available, and refers to the instance of the java.lang.Throwable thrown at runtime by the JSP that caused the error.

Omitted by

errorPage

Omitted by default

isErrorPage

false

contentType

Define the character encoding for the JSP and the MIME type for the response of the JSP Page.

The default Value for the MIMETYPE is This can have either of the form MIMETYPE or MIMETYPE; text/html; charset=CHARSET with an optional white space after the ; the default value for the CHARSET, or character encoding if specified, must be the CHARSET is IANA value for a character encoding ISO-8859-1

Author - Sumit Agarwal (sagarwal10@sapient.com)

The Include Directive The include directive instructs the container to include the content of a resource in the current JSP, inserting it inline, in the JSP page, in place of the directive. The specified file must be accessible and available to the JSP contains. The syntax of the include directive is: <%@ include file = filename %> The only available attribute file specifies the file name of the file to include. This is a relative path within the current WAR, beginning with a forward slash. Note that it is not necessarily a public URL within the WAR, as the include directive has access to all files within a WAR, even those not publicly available. The included content need not always be a JSP; HTML fragments, or any other text resources, may be included. The following are examples of the valid filenames: /debug.jsp /WEB-INF/templates/standardFooter.html The content of the include file is parsed by the JSP only at translation time, that is when the JSP page is compiled into s servlet. Note: Most JSP containers will keep track of the included file and recompile the JSP page if it changes. The container may, however, choose not to do this. Since compilation of the include file will not occur until it has been included in the context of another , complete JSP, the included file does not need to be a valid JSP. it may, for example, rely on imports or beans that it does not declare. In such cases, we should follows these conventions: Use an extension other than JSP for the include file. The JSP specification recommends that we use .jspf or .jsf. Place incomplete page fragments in a directory of our web application that is not publicly available to prevent system users requesting them directly. Anywhere under the WEB-INF directory will do. Document any context requirements of your page fragment (such as variable and import assumption ) in a JSP header comment.

Example : The include file can be either a static file (such as an HTML file) or another JSP page. In either case the result will be the same as if the entire content of the file had been typed into the including JSP page instead of the include directive. Example: 1 The example below, includeDirective1.jsp, requests the inclusion, during compilation, of a copyright.html file containing a legal disclaimer written in HTML:
******************************includeDirective1.jsp****************************** <html> <head> <title> Include Directive Test Page 1 </title> </head> <body><h1> Include Directive Test Page 1 </h1> <%@include file = "copyright.html" %> </body> </html> ***********************************copyright.html******************************** <p>&copy; 2005 java tech ltd.</p>

Author - Sumit Agarwal (sagarwal10@sapient.com)

Example: 2 The next example shows how a JSP page can be included, Consider the file includeDirective2.jsp:
******************************includeDirective2.jsp****************************** <html> <head><title> Include Directive Test Page 2 </title> </head> <body> <h1> Include Directive Test Page 2 </h1> <%@include file = "included.jsp" %> </body> </html> ***********************************included.jsp********************************** <%@ page import = "java.util.Date" %> <%= "Current Date is " + new Date() %>

The taglib Directive


The taglib directive allows the page to the tag extension(custom tags). It names the tag library that contains compiled java code defining the tags to be used. The engine/container uses this tag library to find out what to do when it comes across the custom tags in the JSP. The syntax of the taglib directive is: <%@ taglib uri= tagLibraryURI prefix= tagPrefix %> and the available attributes are: Attribute uri Description A URI (Uniform Resource Identifier) that identifies the tag library descriptor. A tag library descriptor is used to uniquely name the set of custom tags and tells the container what to do with the specified tags. Defines the prefix string in prefix:tagname that is used to define the custom tag. The prefix jsp, jspx, java, javax, servlet, sun, and sunw are reserved. Default value No Default
Not specifying a value causes a Compilation error

tagPrefix

No Default
Not specifying a Value causes a Compilation error

If this value is mytag then when the container comes across any element that start like <mytag:tagname ../> in the JSP, it references the tag library Scripting Element descriptor specified in the URI. JSP scripting elements allows java code variable and method declarations, scriptlets, and expression to be inserted into our JSP page. Declarations A declaration is a block of Java code in a JSP that is used to define class-wide variables and methods in the generated servlets. Declarations are initialized when the JSP page is initialized, and have instance scope in the generated servlet, so that anything defined in a declaration is available throughout the JSP to other declarations, expressions and code. A declaration block is enclose between <%! and %> and does not write anything to the output stream. The syntax is: <%! Java variable and method declarations %> Author - Sumit Agarwal (sagarwal10@sapient.com) 9

Example: 3 consider the simple JSP below, declaration.jsp:


********************************declaration.jsp********************************** <%! int numTimes=3; public String sayHello(String name) { return "Hello," +name + "!"; } %> <html> <head><title>Declaration test page</title></head> <body> <h1>Declaration test page</h1> <p>The value of numtimes is <%= numTimes %>.</p> <p>Saying hello to sumit: "<%= sayHello("Sumit!") %>".</p> </body> </html>

Scriptlets A Scriptlet is a block of java code that is executed during the request- processing time, and is enclosed between <% and %> tags. The Syntax for the Scriptlet is: <% Valid Java Code Statements %> Example: 4 In Scriptlet.jsp below, a scriptlet executer a loop ten times. It includes a message each time in the HTML sent to the browser using the implicit object out. It also sends each message to the System.out stream, that is to the console window in which the web server/container is running.
**********************************Scriptlet.jsp********************************** <html> <head> <title>Scriptlet test page</title> </head> <body> <h1>Scriptlet test page</h1> <% for(int i=0;i<10;i++) { out.println("<b>Java ifotech.This is a scriptlet test " + i + "</b><br>"); System.out.println("This goes to the System.out Stream" + i); } %> </body> </html>

Scriptlets can be broken up by static content so long as compound statements are used in them and the structure of the curly braces is logical. There are no restrictions on the JSP code that may appear within scriptlets (other scriptlets, actions, directives, expressions and template data may be used.
<% if (scott.equals(request.getParameter(userName))){ %> Hello scott. Youre logged in. <% } else { %> Youre not scott. Your user name is <%= request.getParameter(username)%> <% } %> Author - Sumit Agarwal (sagarwal10@sapient.com)

10

Note that code like the following example of incorrect scriptlet usages wont work as expected:
<% if (Scott.equals(request.getParameter(userName))) { Hello Scott. Youre logged in. %>

Expressions An expression is a shorthand notation for a scriptlet that sends the value of a java expression back to the client. The expression is evaluated at HTTP request processing time, and the result is converted to a String and displayed. An expression is enclosed in the <%= and %> tags. If the result of the expression is an object, the conversion is done by using the objects toString()method. The syntax of the Expression is: <%= Java expression to be evaluated %> Example: 5 The expression.jsp below, setup a simple counter and demonstrates declaration, scriptlets, and expressions working together:
******************************** expression.jsp ********************************* <html> <head> <title>Expression test page</title> </head> <body> <h1>Expression test page</h1> <%! int i=0 ; %> <% i++; %> Java tech Ltd. <%= "This JSP has been accessed </body> </html> : {" + i + "} times" %>

Note That while code in scriptlets follows normal Java grammar, encoding statements with a semicolon, a JSP expression, however complicated it may be, does not end with a semicolon. Comments JSP Supports hidden comments. Any content between the delimiters <%-- and --%> will be ignored by the container at translation time. JSP comments dont nest so any content except a terminating --%> is legal within JSP comments. If we want to see comments in the generated output, we can always use HTML or XML comments with the <!- and -> delimiters; these will simply be treated as normal template date by the container. We can use JSP comments to document details of our implementation as we do in java code. However, we could choose to use just JSP comments rather than HTML comments to document our markup structure as well. This means that we can be as verbose as we like without bloating the generated content. We can also use the standard Java comment syntax within JSP scriptlet elements.

Author - Sumit Agarwal (sagarwal10@sapient.com)

11

Implicit Objects
JSP provides certain implicit objects, based on the Servlet API. These objects are access using standard variables, and are automatically available for use in our JSP without writing any extra code. The implicit objects available in a JSP page are: request, response page, session, application pageContext config out exception

The request Object The request object has request scope, and is an instance of the javax.servlet.ServletRequest class. It encapsulates the request coming from the Client and being processed by the JSP. It is passed to the JSP by the container as a parameter of the _jspService( ) method. It has request scope. The response object The response object has page scope, and is an instance of javax.servlet.ServletResponse It encapsulates the response generated by the JSP to be send back to the client in response to the request. It is generated by the container and passed to the JSP as a parameter to the _jspService( ) method, where it is modified by the JSP. It is legal to set HTTP status code and headers in the JSP page once output has been send to the client, as JSP output streams are buffered by default. The pageContext objects The pageContext provides a single point of access to many of the page attribute and is convenient place to put shared data within the page. It is of type javax.servlet.jsp.pageContext and has page scope. The session object The session object represents the session created for the requesting client. Session are created automatically, and a new session is available even when there is no incoming session (unless, of course, you have used a session=false attribute in the page directive, in which case this variable will not be available). The session object is of type javax.servlet.http.HttpSession and has session scope. The application object The application object represents the servlet context, obtained from the servlet configuration object. It is of type javax.servlet.ServletContext and has application scope. The out object The out object is the object that writes into the output stream to the client. To make the response object useful, this is a buffered version of the javax.servlet.jsp.JspWriter.The buffer size can be adjusted by the buffer attribute of the page directive. The config object The config is the ServletConfig for the JSP page and has page scope. It is of type javax.servlet.ServletConfig.

Author - Sumit Agarwal (sagarwal10@sapient.com)

12

The page object The page object is an instance of the pages implementation servlet class that is processing the current request. It is of type java.lang.Object, and has page scope. The page object can be thought of as a synonym to this within the page.

Scope
The scope of JSP objects- JavaBeans and implicit objects is critical, as it defines the how long, and from which JSP pages, the object will be available. Page Scope Request Scope Session Scope Application Scope

Page Scope An object with page scope is bound to javax.servlet.jsp.PageContext. The object is placed in the PageContext object for as long as the page is responding to the current request. An object with this scope can be accessed by invoking the getAttribute( ) method on the implicit page Context object. The object is created and destroyed for each client request to the page. This is the default scope for objects used with the <jsp:useBean> action. Request Scope Request scope means that the object is bound to the javax.servlet.ServletRequest, and can be accessed by invoking the getAttribute( ) method on the implicit request object. The object is distinct for every client request. The object reference is available as long as the HttpRequest object exists, even if the request is forwarded to different page, or if the <jsp:include> action is used. Session Scope An object with session scope is bound to the javax.servlet.jsp.PageContext, and can be accessed by invoking getValue( ) method on the implicit session object. The generated servlet relies on binding the object to the HttpSession using the setAttribute(String key, Object value) method. The object is different for every client, and is available as long as the clients session is valid. Application Scope Application Scope means that the object is bound to the javax.servlet.ServletContext. An object with this scope can be accessed by invoking the getAttribute( ) method on implicit application object. This is the most persistence scope. When accessing application variables, take care your code is thread safe. Application variables are often populated on application startup, and read only thereafter.

Author - Sumit Agarwal (sagarwal10@sapient.com)

13

Java Beans A Bean is simply a java class that follows a set of simple naming and design conventions outlined by the Java bean specification. Beans are not required to extend a specific base class or implement a particular interface. If a class follows these bean convention and you treat it like a bean. Then its a bean. Bean Conventions Beans are just objects. Class naming conventions: Beans follows the same class naming rules as other java classes: they must start with an alphabetic character, contain only alphanumeric and underscore character and be case sensitive. The magic of Introspection/Reflection JSP containers interact with any bean object without using a common interface or bean class through a process called introspection that allows a class to expose its method and capability on request. The introspection process happens at run-time and is controlled by the bean container. Introspections allow us to rely on conventions to establish properties. Introspection occur through mechanism known as reflection, which allows the bean container to examine any class at run time to determine its method signatures. The Bean Constructor You must implement a constructor that takes no arguments. It is this constructor that the JSP container will use to instantiated your bean through the <jsp:useBean> tag. Defining a Bean properties: A Bean property is defined simply by creating appropriate access method for them. Access methods are used either to retrieve properties value or make changes to it. A method used to retrieve a propertys values is called a getter method, while a method that modifies its value is called a setter method. To define a property for a bean simply create public method with the name of the property you wish to define prefixed with the word get or set as appropriate. Getter method should return the appropriate data type while the corresponding setter method should be declared void & accept the arguments of the appropriate type. Signature is public void setPropertyName(PropertyType value); public PropertyType getPropertyName( ); for Example: public void setAge(int age); public int getAge( ); The JSP container will not recognize properties without public access method. Property Name Convention Beginning with a lowercase letter and uppercasing the first letter of each word in the property name. Example: Property :- firstName,secondName Getter methods: - getFirstName( ), getSecondName( ) Indexed Properties For Multivalued properties with getters public PropertyType[] getProperty( ) public PropertyType getProperty(int index) For Multivalued properties with setters public void setProperty(int index, PropertyValue value) Author - Sumit Agarwal (sagarwal10@sapient.com) 14

public void setProperty(PropertyType[] value) Accessing indexed value through JSP bean tags Since bean tags deal execlusively with single values, we will have to program the conversion ourselves in the property access method. A JSP components properties are not limited to string value, but it is important to enclosed that all property value accessed through the <jsp:getProperty> tag will be commented into a string. A getter method need not return a String explicitly as the jsp contains all automatically convert the return value in a String. boolean------java.lang.Boolean.toString(boolean) byte---------- java.lang.Byte.toString(byte)

JSP Type Conventions

Standard Actions
Standard actions are well- known tags that affect the runtime behavior of the JSP and the response send back to the client. They must be implemented to behave the same way by all containers. Unlike custom tags these actions are available by default and do not require taglib declarations in order use them. When the container comes across a standard action tag during the conversion of a JSP page into a servlet, it generates the Java code that corresponds to the required predefined task. <jsp:useBean> The <jsp:useBean> action is used to instantiate a JavaBean, or to locate an existing bean instance, and assign to a variable name (or id).We can also specify the lifetime of the object by giving it a specific scope. Two form of syntax 1.Without Body <jsp:useBean id= name scope= scopename bean_detail /> 2.With Body <jsp:useBean id= name scope= scopename bean_detail > JSP Body </jsp:useBean> Where bean_details is one of: class=className class=className type=typeName beanName=beanName type=typeName type=typeName

Author - Sumit Agarwal (sagarwal10@sapient.com)

15

The possible Attribute are: Attribute Description id The Case sensitive name used to identify the object instance. If the bean was created by a servlet and made available to the JSP page using the setAttribute( ) method, the id of the <jsp:useBean> action must match the name given to the attribute. scope class beanName The scope within which the reference is available. Possible values are page, request, session or application The fully qualified class name . The name of a bean as we would supply to the instantiate() method in the java.bean .Beans class. This attribute can also be a request- time expression. It is permissible to supply a type and a beanName, and omit the class attribute. The beanName follows the standard bean specification and can be of the form a.b.c is either a class, or the name of a serialized resource in which case it is resolved as a/b/c.ser. type

Default value
No Default Value

page
No Default Value

No Default Value

This optional attribute specifies the type of the scripting variable The Value to be created, and follows standard Java casting rules. The type of the class must be a superclass of the beans class, an interface implemented attribute by it, or the beans class itself. Just like any casting operation, if the object is not of this type then java.lang.ClassCastException can be thrown at request time.

Example: 6 This Example Demonstrate the <jsp:useBean> Action Tag (TimeBean.java, CurrentTimeBean.jsp) .
****************************** CurrentTimeBean.jsp ****************************** <jsp:useBean id="timebean" class="org.bean.TimeBean" /> <html> <title>Time Bean</title> <body> It is now <jsp:getProperty name = "timebean" property = "hours"/> hrs and <jsp:getProperty name = "timebean" property = "minutes"/> minutes </body> </html>

Author - Sumit Agarwal (sagarwal10@sapient.com)

16

***************************** TimeBean.java ************************************ package org.bean; import java.util.*; /** * @author sumit agarwal */ public class TimeBean { private int hours; private int minutes; public TimeBean() { Calendar now = Calendar.getInstance(); this.hours = now.get(Calendar.HOUR_OF_DAY); this.minutes = now.get(Calendar.MINUTE); } public int getHours() { return hours; } public int getMinutes() { return minutes; } }//class

<jsp:setProperty> The <jsp:setProperty> standard tag is used in conjunction with the <jsp:useBean> action described in the preceding section, to set bean properties. Bean properties can be either simple or indexed. The property names follows JavaBean conventions. The properties in the bean can be set either: At request time from parameters in the request object At request time from an evaluated expression. From a specified string, or hard coded in the page. When setting bean properties from the request object, the JSP can choose to set all properties in the JavaBean via the standard action: <jsp:setProperty name= help property= */> or a single property can be set explicitly by an action such as: <jsp:setProperty name= help property= word/> The <jsp:setProperty> action uses the java beans introspection mechanism to discover what properties are present, their names, whether they are simple or indexed, their type, and their access and mutator methods The syntax of the <jsp:setProperty > action is: <jsp:setProperty name= beanName property_details /> Where property_details is one of: property = * property = propertyName property = propertyName param = parameterName property = propertyName value = propertyValue
.

Author - Sumit Agarwal (sagarwal10@sapient.com)

17

Note that propertyValue is a string or a scriptlet. The Attribute is: Attribute name Description The name of a bean instance, which must already have been defined by a <jsp:useBean> tag. The value of this attribute in <jsp:setProperty> must be the same as the value of the id attribute in <jsp:useBean>. The name of the bean property whose value is being set. If this attribute has the value *, the tag looks through all the parameters in the request object and tries to match the request parameter names and types to property names and types in the bean. The values in the request are assigned to each matching bean property unless a request parameter has the value , in which case the bean property is left unaltered. param When setting bean properties from request parameters, it is not necessary for the bean have the same property names as the request parameters. This attribute is used to specify the name of the request parameter whose value we want to assign to a bean property. If the param value is not specified, it is assumed that the request parameters and the bean property have the same name. If there is no request parameters with this name, or if it has the value , the action has no effect on the bean. The value to assign to the bean property. This can be a request time attribute, or It can accept an expression as its value. A tag cannot have both param and value attributes.

property

Value

<jsp:getProperty> The <jsp:getProperty> action is complementary to the <jsp:setProperty> action, and is used to access the properties of a bean. It accesses the value of a property, converts it to a string, and prints it to the output stream to the client. To convert the property to a string, the action: Invokes the toString()method on the property, if it is an object. Converts the value directly to a string, if it is a primitive, using the valueOf()method of the corresponding wrapper class for the primitive type. This is just like the behavior of the System.out.println() method. The Syntax is: <jsp:getProperty name= name property= propertyName /> The available attributes are: Attribute name Property Description The id of the bean instance from which the property is obtained. The name of the to get; this is the instance variable in the bean. Of course, we must Create a bean before using <jsp:getProperty>. 18

Author - Sumit Agarwal (sagarwal10@sapient.com)

Example: 6A This Example Demonstrate the <jsp:useBean>, <jsp:setProperty>, <jsp:getProperty> Action Tag (beans.html, beans.jsp, LanguageBean.java) .
*********************************** beans.html ********************************** <html> <head><title>Bean-Bean</title> </head> <body> <h1>useBean action test page</h1> <form method = "POST" action = "bean.jsp"> <p>Please enter your username: <input type = "text" name = "name"> <br>What is your favorite programming language? <select name = "language"> <option value="Java">Java <option value="C++">C++ <option value="Perl" selected>Perl <option value="Fortran">Fortran </select> </p> <p><input type="submit" value = "Submit Info"> </body> </html> *********************************** bean.jsp *********************************** <jsp:useBean id="languageBean" class="org.bean.LanguageBean"> <jsp:setProperty name = "languageBean" property = "*"/> </jsp:useBean> <html> <head> <title>Language Bean</title> </head> <body> <h2>useBean, getProperty, setProperty action test page</h2> <p>Hello, <jsp:getProperty name = "languageBean" property = "name"/>.</p> <p>Your favorite language is <jsp:getProperty name = "languageBean" property = "language"/>.</p> <p>My Comments on this language:</p> <jsp:getProperty name = "languageBean" property = "languageComments"/>.</p> <%= request.getParameter("name") %> <jsp:getProperty name = "languageBean" property = "enabled"/> </body> </html>

Author - Sumit Agarwal (sagarwal10@sapient.com)

19

******************************* LanguageBean.java ******************************* package org.bean; public class LanguageBean { private String name; private String language = ""; public boolean isEnabled() { return true; } public LanguageBean() { } public void setName(String name) { this.name = name; } public void setLanguage(String language) { this.language = language; } public String getName() { return name; } public String getLanguage() { return language; } public String getLanguageComments() { if (language.equals("Java")) { return "The king of OO languages."; } else if (language.equals("C++")) { return "Rather too complex"; } else if (language.equals("Perl")) { return "OK if you like incomprehensible code."; } else { return "Sorry, I have never herd of " + language + "."; } } }

Author - Sumit Agarwal (sagarwal10@sapient.com)

20

The Example: Navigate to http://localhost:8080/servlets/bean.html, and you will see the following page:

Enter your name and choose your favored language, then click the Submit Info button you will see the output in following page.

Author - Sumit Agarwal (sagarwal10@sapient.com)

21

Example: 7 Accessing The Indexed Bean Properties (IndexedBean1.jsp, IndexedBean2.jsp, IndexedBean.java).


******************************* IndexedBean1.jsp ******************************** <jsp:useBean id="indexedBean" class="org.bean.IndexedBean"> <% double numbers[] = {11,12,13,14,15,16}; indexedBean.setNumbers(numbers); %> </jsp:useBean> <html> <head><title>Index Bean</title></head> <body> The average of <% double numbers[] = indexedBean.getNumbers(); for(int i=0; i<numbers.length; i++) { if(i != numbers.length-1) out.println(numbers[i] + ","); else out.println("" + numbers[i]); } %> is equal to <jsp:getProperty name = "indexedBean" property = "average"/>.</p> </body> </html> ******************************* IndexedBean2.jsp ******************************** <jsp:useBean id="indexedBean" class="org.bean.IndexedBean"> <% a = new double[2]; a[0] = 10; a[1] = 20; %> </jsp:useBean> <html> <head> <title>Index Bean</title> </head> <body> <%! double a[]; %> <jsp:setProperty name = "indexedBean" property = "numberList" value="100,200,300,400,500,600"/> The average of <jsp:getProperty name = "indexedBean" property = "numberList"/> is equal to <jsp:getProperty name = "indexedBean" property = "average"/> </body> </html>

Author - Sumit Agarwal (sagarwal10@sapient.com)

22

******************************* IndexedBean.java ******************************** package org.bean; import java.util.Vector; import java.util.StringTokenizer; public class IndexedBean { private double a[] = { 11, 12, 13 }; public IndexedBean() { } public double getAverage() { double sum = 0; for (int i = 0; i < a.length; i++) sum = sum + a[i]; return sum / a.length; } public double[] getNumbers() { return a; } public double getNumber(int index) { return a[index]; } public void setNumbers(double b[]) { a = b; } public void setNumber(int index, double value) { a[index] = value; } public void setNumberList(String values) { Vector n = new Vector(); StringTokenizer tok = new StringTokenizer(values, ","); while (tok.hasMoreTokens()) n.addElement(tok.nextToken()); a = new double[n.size()]; for (int i = 0; i < a.length; i++) a[i] = Double.parseDouble((String) n.elementAt(i)); } public String getNumberList() { String list = new String(); for (int i = 0; i < a.length; i++) { if (i != a.length - 1) list = list + a[i] + ","; else list = list + a[i]; } return list; } }

Author - Sumit Agarwal (sagarwal10@sapient.com)

23

The Output of the IndexedBean1.jsp is given below:

The Output of the IndexedBean2.jsp is given below:

Author - Sumit Agarwal (sagarwal10@sapient.com)

24

Example: 8 Iterating The Planet Bean using an Array (PlanetBean.jsp, PlanetBean.java).


******************************** PlanetBean.jsp ********************************* <jsp:useBean id="planetBean" class="org.bean.PlanetBean"/> <html> <head><title>Planet Bean Using Array</title></head> <body> <table border="1"> <tr><th>Planet</th><th>Number of Moons</th></tr> <% while(planetBean.next()){ %> <tr> <td><jsp:getProperty name = "planetBean" property = "name"/></td> <td align = "Center"><jsp:getProperty name = "planetBean" property = "moonCount"/></td> </tr> <% } %> </table> </body> </html> ******************************* PlanetBean.java ********************************* package org.bean; public class PlanetBean { public int index = 0; private static final int numPlanets = 9; private static final String[] names = { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto" }; private static final int[] moons = { 0, 0, 1, 2, 16, 18, 20, 8, 1 }; public PlanetBean() { index = -1; } public void first() { index = -1; } public String getName() { System.out.println("index = " + index); return names[index]; } public int getMoonCount() { return moons[index]; } public boolean next() { ++index; if (index == numPlanets) { --index; return false; } else return true; } }

Author - Sumit Agarwal (sagarwal10@sapient.com)

25

The Output of The above Application is:

Author - Sumit Agarwal (sagarwal10@sapient.com)

26

<jsp:include> This action allows static and a dynamic resource, specified by a URL, to be included in the current JSP at request-processing time. An included page has access only to the JspWriter object, and it cannot set headers or cookies. A request-time exception is thrown if this is attempted. This constraint is Equivalent to that imposed on the include()method of javax.servlet.RequestDispatcher used by servlet for this type of inclusion. If the page output is buffered, the developer can choose whether the buffer should be flushed prior to the inclusion. The syntax of the <jsp:include> action is: <jsp:include page = URL flush = true /> or: <jsp:include page = URL flush = true> <jsp:param name = paramname value = paramvalue /> ... </jsp:include> The attributes of the <jsp:include> action are: Attribute page flush Description The resource to include. The URL format is the same as described earlier for the include directive. This attribute is optional, with the default value of false. If the value is true, The buffer in the output stream is flushed before the inclusion is performed.

A <jsp:include> action may have one or more <jsp:param> tags in its body, providing additional name-value pairs. The included page can access the original request object, which will contain both the original parameters, and the new parameters specified using the <jsp:param> tag. If the parameter names are the same, the old values are kept intact, but the new values take precedence over the existing values. The attributes can be extracted from the request using the getParameter(String paramname) method in the javax.servlet.ServletRequest interface. It is important to understand the difference between the include directive and this include action: Include Type directive action Syntax Takes Place Compilation Included Content Static Static or Dynamic Parsing Parsed by Container Not parsed but included in place.The Specified URL is Specified at run time as separate resource. The included URL may map to a servlet, rather than a JSP. 27

<%@ include file=filename %> <jsp:include Requestpage = URL /> Processing Time

Author - Sumit Agarwal (sagarwal10@sapient.com)

The include directive lets us include resources into multiple pages but requires the including pages to be retranslated if any included resources change. This means that unless our JSP container is smart enough to store and check dependency information at request processing time, we may need to update the modification date on all pages statically, including a modified page fragment, to ensure that they are updated. The include action includes the files at request-processing time. Use the include directive if your resources is not going to change frequently Use the include action when the resource changes frequently or is dynamic. Lets look in the following example: Example: 10 This Example Demonstrate The <jsp:include> Action Tag. (IncludeAction.jsp, Included2.jsp, Included2.html)
******************************* IncludeAction.jsp ******************************* <html> <head> <title> Include Action Test Page </title> </head> <body> <h1> Include Action Test Page </h1> <h2> Using the Include Directive </h2> <%@include file = "Included2.html" %> <%@include file = "Included2.jsp" %> <h2> Using the Include Action </h2> <jsp:include page="Included2.html"/> <jsp:include page="Included2.jsp"/> </body> </html> *********************************** Included2.jsp ******************************* <%@ page import = "java.util.Date" %> <%= "Current Date is " + new Date() %> *********************************** Included2.html ****************************** <p>This is some static text in the HTML file...........</p>

Start the Tomcat web server and then request http://localhost:8080/servlets/IncludeAction.jsp you get the following page on screen:

Author - Sumit Agarwal (sagarwal10@sapient.com)

28

<jsp:forward> The <jsp:forward> action allows the request to be forwarded to another JSP, a servlet, or a static resource. This is particularly useful when we want to separate the application into different views, depending on the intercepted request. The syntax of the <jsp:forward> action is: <jsp:forward page = URL /> or: <jsp:forward page = URL> <jsp:param name = paramname value = paramvalue /> ... </jsp:forward> The resource to which the request is being forwarded must be in the same web application. Execution in the current JSP stops when it encounters a <jsp:forward> tag. The buffer is cleared and the request is modified to assimilate any additional specified parameters. If the output stream was not buffered, and the some output has been written to it, a <jsp:forward> action will throw a java.lang.IllegalStateException. Example: 11 This Example Demonstrates the <jsp:forward> Action tag using a simple Login form. The Login form forward.html is straightforward, sending a POST request to forward.jsp. (forward.html, forward.jsp, forward2.jsp)
*********************************** forward.html ******************************** <html> <head><title>Forward Action Test Page</title></head> <body> <h1>Forward action Test Page</h1> <form method="post" action="forward.jsp"> <p>Please Enter Your username: <input type="text" name="userName"> <br> and Password: <input type="password" name="password"></p> <p><input type="submit" value="Login"> </form> </body> </html>

*********************************** forward.jsp ********************************* <% if ((request.getParameter("userName").equals("sumit")) && (request.getParameter("password").equals("agarwal"))) { %> <jsp:forward page="forward2.jsp" /> <% } else { %> <%@ include file="forward.html"%> <%}%>

Author - Sumit Agarwal (sagarwal10@sapient.com)

29

*********************************** forward2.jsp ******************************** <html> <head> <title>Forward action test:Login successful !</title> </head> <body> <h1>Forward action test: Login Successful</h1> <p>Welcome, <%= request.getParameter("userName") %> </body> </html>

Request the http://localhost:8080/servlets/forward.html you get the following page on screen:

Entering the username Sumit and password agarwal, we get to this page:

Author - Sumit Agarwal (sagarwal10@sapient.com)

30

<jsp:plugin> The <jsp:plugin> action provides easy support for including Java applets in JSP-generated pages. It is used to generate browser-specific HTML tags (<object> or <embed>) that result in the download of the java plug-in software, If required, followed by the execution of the applet or JavaBean component that is specified in the tag. (This relies on JSP detecting our browser by parsing it user agent string.) The <jsp:plugin> tag has two optional support tag: <jsp:params>- to pass additional parameters to the applet or JavaBeans component <jsp:fallback>- to specify the content to be displayed in the client browser if the plug-in cannot be started because the generated tags are not supported. The <jsp:fallback> tag works like the <noframes> tag. The syntax of the <jsp:plugin>action is: <jsp:plugin type= bean|applet code= objectCode codebase= objectCodebase align= alignment archive= archivList height= height hspace= hspace jreversion= jreversion name= comonentName vspace= vspace width= width nspluginurl= url iepluginurl= url > <jsp:params> <jsp:param name= paramName value= paramValue /> <jsp:param name = paramName value = paramValue /> ... </jsp:params> <jsp:fallback> Alternate text to display </jsp:fallback> </jsp:plugin>

Author - Sumit Agarwal (sagarwal10@sapient.com)

31

The available attribute for the <jsp:plugin> is: Attribute type code codebase align archive height Details Identifies the type of the component: a JavaBean, or an Applet. Same as HTML syntax. Same as HTML syntax. Same as HTML syntax. Same as HTML syntax. Same as HTML syntax. Required Yes Yes No No No No, but some browsers do not allow an object of zero height due to security issues No No No No No No, but some browsers do not allow an object of zero width due to security issues. No No

hspace jreversion name vspace title width

Same as HTML syntax. The Java runtime environment version needed to execute this object. Default is 1.1. Same as HTML syntax. Same as HTML syntax. Same as HTML syntax. Same as HTML syntax.

nspluginurl URL where the java plugin can be downloaded for Netscape Navigator. Default is implementation defined. iepluginurl URL where the java plugin can be downloaded Internet Explorer. Default is implementation defined.

Author - Sumit Agarwal (sagarwal10@sapient.com)

32

<jsp:params> The <jsp:params> standard action can occur only within the body of the <jsp:plugin> tag. It is used to group a set of <jsp:param> entries. The Syntax of the <jsp:params> is: <jsp:params> <jsp:param <jsp:param </jsp:params> /> />

There can be any number of <jsp:param> standard actions in the body of the <jsp:params> tag. Each will be translated to a parameter for the applet and /or bean embedded on the Web page. <jsp:param> The <jsp:param> action is used to provide other, enclosing, tags with additional information in the form of name-value pairs. It is used in conjunction with the <jsp:include>,<jsp:forward>, and <jsp:plugin> actions, and its use is described in the relevant sections that follows.

The syntax of the <jsp:param> is: <jsp:param name=paramname value = paramvalue /> The available attributes are: Attribute Name Value Description The key associated with the attribute. (Attributes are key-value pairs.) The value of the attribute.

<jsp:fallback> The <jsp:fallback> standard action can be used only within the body of the <jsp:plugin> tag. This standard action specifies the HTML that will be rendered (or the JSP code that will be executed) if the browser does not support the plugin. The basic Syntax for <jsp:fallback> is as follows: <jsp:fallback>
HTML or JSP that will be rendered if the browser does not support plugin.

</jsp:fallback> Note: - There is several other standard JSP actions that are only used in the creation of tag files. (<jsp:attribute>,<jsp:body>,<jsp:invoke>,<jsp:doBody>,<jsp:element>,<jsp:text>,<jsp:output>) Author - Sumit Agarwal (sagarwal10@sapient.com) 33

Example: 12 This Example Demonstrate The <jsp:plugin>, <jsp:params>, <jsp:param> and <jsp:fallback> Action Tag. (plugin.jsp, SimpleApplet.java).
*********************************** plugin.jsp ********************************** <html> <title> Plugin example </title> <body bgcolor="white"> <h3> Plugin Applet: </h3> <jsp:plugin type="applet" code="org.plugin.SimpleApplet" codebase="applet" jreversion="1.2" width="500" height="200"> <jsp:params> <jsp:param name="x_cor" value="150"/> <jsp:param name="y_cor" value="100"/> </jsp:params> <jsp:fallback> Unable to Start Plugin browser not suported. </jsp:fallback> </jsp:plugin> <p> <h4> <font color=lime> The applet is loaded using the plugin tag. </font> </h4> </body> </html> *********************************SimpleApplet.java******************************* package org.plugin; import java.awt.*; import java.applet.*; /** * @author sagar8 * */ public class SimpleApplet extends Applet { private int x = 20; private int y = 20; public void init() { setBackground(Color.blue); setForeground(Color.red); setFont(new Font("",Font.PLAIN,20)); x = Integer.parseInt(this.getParameter("x_cor")); y = Integer.parseInt(this.getParameter("y_cor")); } public void paint(Graphics g) { g.drawString("Sumit Agarwal", x, y); } }//class

Author - Sumit Agarwal (sagarwal10@sapient.com)

34

Start the Tomcat web server and then request http://localhost:8080/servlets/plugin.jsp you get the following page on screen:

Author - Sumit Agarwal (sagarwal10@sapient.com)

35

JSP Tag Extension


Well-designed tag extensions libraries can enable application functionality to be invoked without the appearance of programming. The Key concept in tag extensions is: Tag Name: A JSP tag is originally identified by a combination of prefix and suffix. <jsp:forward page = next.jsp>

Prefix

suffix

Attributes: Tags may have attributes, which use the XML syntax for attributes. The <jsp:forward> tag above has one attribute<page> while the <jsp:param> attribute has two (name and value). Attribute may be required or optional. <jsp:forward page=next.jsp> <jsp:param name= image value= house.gif /> </jsp:forward> Nesting: Tag extension can detect nested tags at runtime and cooperate. A tag directly enclosing another tag is called the parent of the tag it encloses. In above example <jsp:forward> tag is the parent of the <jsp:param> tag. Body content: This body content is anything between the start and end elements in a JSP tag excluding sub tags. A tag extension can access & manipulate its body content. Neither the <jsp:forward> nor <jsp:param> tags require body content. For Example: <example:hello>This is Example of display Hello</example:hello> Scripting variables: Tags can define variables that can be used within the JSP page in tag body content or (depending on the scope of the variables) after the tag has been closed. The <jsp:useBean> standard action is an example of a tag that defines a scripting variables available throughout the reminder of the JSP. Typical Use of tag extension is: To mark the complexity of access to a data source or enterprise object from the page. To introduced new scripting variables into the page. To filter or transform tag content or even interpret it as another language. To handle iteration without the need for scriptlets. Difference between beans and tag extensions: Tag extensions are common building blocks not tailored resources for a particular page or group of pages. Tags receive the attribute that controls their behavior from the JSP pages using them, not from the request to a particular JSP. A well-designed tag extension may be used in many JSP pages.

Author - Sumit Agarwal (sagarwal10@sapient.com)

36

Example: 13 A Simple Tag Example (Before we look at the tag extension API and the supporting Infrastructure in details, Lets Implement a Simple Tag.(Hello.jsp, HelloTag.java, Hello.tld, web.xml).
************************************* Hello.jsp ********************************* <%@ taglib uri="/hello" prefix="examples" %> <%-- imports tag named 'hello' --%> <html> <head> <title>My First Custom Tag</title> </head> <body> <p>This is static output. Tag output is shown in italics.</p> <p><i> <examples:hello/> </i></p> <p>This is static template data again </p> </body> </html>

To implement the Tag we need to define a tag handler (a java class implementing the tags functionality), and provide a tag library descriptor. We can then import the tag library into any JSP page that require it. The TagHandler class (HelloTag.java) must react to callbacks from the JSP engine when it encounters tags in JSP pages at run time. The most Important of these callbacks are doStartTag() which is called when the closing tag is encountered. The implementation of the HelloTag is very simple, as most of the work of implementing the custom tag is done by the TagSupport superclass provided by the JSP API.

********************************* HelloTag.java ********************************* package tagext; import import import import java.io.IOException; java.util.Date; javax.servlet.jsp.*; javax.servlet.jsp.tagext.TagSupport;

public class HelloTag extends TagSupport { public int doStartTag() throws JspTagException { return EVAL_BODY_INCLUDE; } public int doEndTag() throws JspTagException { String dateString = new Date().toString(); try{ pageContext.getOut().write("Hello world.<br/>"); pageContext.getOut().write("My name is " + getClass().getName() + " and it's " + dateString + "<p/>"); }catch(IOException e) { throw new JspTagException("Fatal error: hello tag couldn't write to JSP out"); } return EVAL_PAGE; } }

Author - Sumit Agarwal (sagarwal10@sapient.com)

37

The TagSupport superclass is a convenience class provided in the tag extension API. It already implements the javax.servlet.jsp.tagext.Tag interface: The doStartTag() method return a value indicating that the EVAL_BODY_INCLUDE (means to evaluate the tags body content and any sub-tags) and SKIP_BODY (meaning tag contents will be ignored). The doEndTag() method return the values are EVAL_PAGE (the usual case), and SKIP_PAGE. The Tag Library Descriptor, which we will name Hello.tld, maps the Tags to the Tag handler class.
*********************************** Hello.tld *********************************** <?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.2</jsp-version> <short-name>examples</short-name> <description> Simple example library. Author: Sumit </description> <tag> <name>hello</name> <tag-class>tagext.HelloTag</tag-class> <body-content>JSP</body-content> <description>Simple hello world example. Takes no attributes, and simply generates html </description> </tag> </taglib>

*********************************** web.xml ************************************* <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <display-name>Hello Tag</display-name> <description> Tag extension example (Tag without aattributs) </description> <taglib> <taglib-uri>/hello</taglib-uri> <taglib-location>/WEB-INF/tlds/Hello.tld</taglib-location> </taglib> </web-app>

Author - Sumit Agarwal (sagarwal10@sapient.com)

38

Note: - As a tag library can include any number of tags, we will simply add extra <tag> elements to this tag library descriptor in the next example. The Directory Structure to deploy this Application. Hello.jsp WEB-INF/ web.xml classes/ tagext/ HelloTag.class tlds/ Hello.tld Start the Tomcat web server and then navigate to http://localhost:8080/HelloTag/Hello.jsp you will get the following output:

Anatomy of a Tag extension


A number of components are required to implement a tag extension. The minimal requirement is a tag handler and a tag library descriptor. A tag handler is a JavaBean that implements one of three interfaces defind in the javax.servlet.jsp.tagext package: Tag, IterationTag, or BodyTag. These interfaces define the LifeCycle events relevant to a tag. Most importantly, the calls that the class implementing the tag will receive when the jsp engine encounters the opening and closing tags. A tag library descriptor or TLD, which is an XML document that contains information about one or more tag extensions. An additional class may also be specified in the TLD that performs customs validation of tag attributes (TagLibraryValidator class) Author - Sumit Agarwal (sagarwal10@sapient.com) 39

Tag Handlers
The javax.servlet.jsp.tagext.Tag Interface The Tag Interface defines a simple interaction between the JSP engine and tag handle which is sufficient tags that do not need to manipulate their body content or evaluate it repeatedly. Methods calls by the JSP container to tag. JSP Page Tag

setPageContaxt(pageContext)

setParent(enclosingTag)

setAttribute1

doStartTag

doEndTag

release

Author - Sumit Agarwal (sagarwal10@sapient.com)

40

The doStartTag() and doEndTag() methods: public int doStartTag() throws JspException This is called after the tag has been initialized, its return values should be one or two constants defined in the tag interface: EVAL_BODY_INCLUDE, which instruct the JSP engine to evaluate both the tags body and any child tags it has, or SKIP_BODY, which instruct the JSP engine to ignore the body. public int doEndTag() throws JspException This method is called when the JSP engine encounters the enclosing tag of an element at run time. Its return value can be EVAL_PAGE or SKIP_PAGE. javax.servlet.jsp.tagext.IterationTag Interface The interface has been added in jsp1.2, and extends Tag interface. Its adds single new method that allow tag to repeat the evaluation of tag body content: int doAfterBody() throws JspException doAfterBody( ) is called each time the tags body has been processed (where doEndTag( ) would have been called in the case of an implementation of the Tag interface ). The valid return values are: a. EVAL_BODY_AGAIN and b. SKIP_BODY Note: - In JSP 1.1, it was necessary to use the BodyTag interface to perform iteration. The introduction of much simpler IterationTag interface result in simplification, or the BodyTag interface introduces unnecessary complexity in the case of simple looping constructs. The javax.servlet.jsp.tagext.BodyTag Interface BodyTag extends IterationTag, adding extra callbacks and other methods and allowing the developer to work with the tags body content. Note: In JSP1.1, BodyTag extended Tag. However the change is backward compatible, as the doAfterBody( ) method has merely been moved from BodyTag into the new Iteration Tag interface. A Sequence Diagram that display the Iteration between calling JSP and tag handler in the case of a body tag is much more complex than that of the Tag interface are shown in the next page: The more significant methods of the BodyTag interface: setBodyContent(BodyContent bodyContent) The initialization method is used to set the object used to manipulate the body content. It is only invoked if doStartTag() returned EVAL_BODY_BUFFERED. doInitBody()throws JSP Exception This method is invoked by the JSP engine only if doStartTag() returned EVAL_BODY_BUFFERED. In this case, it is invoked after setBodyContent() doAfterBody()throws JSP Exception This method is inherited from the IterationTag interface and work in the same way. As for IterationTags, valid return values are EVAL_BODY_AGAIN and SKIP_BODY.

Continue with diagrams in the next page Author - Sumit Agarwal (sagarwal10@sapient.com) 41

JSP Page

BodyTag

PageContext

Author - Sumit Agarwal (sagarwal10@sapient.com)

42

The javax.servlet.jsp.tagext.BodyContent Class The BodyContent class is the key to the buffered BodyTag functionality. BodyContent is a subclass of JSPWriter that can be used to manipulate the body content of BodyTag implementation and store it for later retrieval. The getBodyContent()method of BodyTagSupport returns the BodyContent instance associated with the particular tag. The javax.servlet.jsp.tagext.TagExtraInfo class Metadata class extending the TagExtraInfo abstract class may be associated with tag handler to provide extra information to a JSP page. This optional associated is specified in the tag library descriptor. Two methods you can most likely to override are VariableInfo[] getVariableInfo(TagData td) This method is used to return information about scripting variable that the tag make available to JSPs using it. It return an array of variableInfo objects which contain information about the name of each scripting variable & its fully qualified class name. boolean isValid(TagData data) This is some time used for validate the attributes passed to a atag at translation time. As an example, consider a tag with four attributes. Three way to optional, but if one of the optional attribute is specified the whole three must be present. There is no way to specify this behaviour in a tag library descriptor. However the isValid( ) method of the appropriate TagExtraInfo subclass could be implemented to return false if the parameter supplied at transition time are invalid. The default implementation of isValid() in TagExtraInfo always return true. Note that the runtime attribute validation is entirely different and is the responsibility of the tag handler concerned. Deploying & Packaging Tab Libraries There are three main ways of deploying and using tag libraries with a JSP engine. Mapping in web.xml Packaging the tag libraries or JARs. A Tag Library may be distributed in a JAR file in which the META-INF subdirectory contains the tag library descriptor named taglib.tld. The JAR file should also contain the classes required to implement the Tags defined in the tag library, but will not contain the JSP pages that use the Tag Library. In this case, the taglib directive in JSP pages should refer to this JAR, which will probably be written a WAR. This enables custom tags to be supplied in self-contained units a vital precondition for the successful distributor of third party custom tags. <%@ taglib url=/WEB-INF/lib/hellotags.jar prefix=examples %> When including such a tag library JAR in a web application, we place it under the |WEB-INF|lib Directory, to ensure that the classes it contains will be on the application path. Default Mapping: <%@ taglib url = ./hello.tld prefix = examples %> The simplest means of deployment is to simply place the TLD under the servers document root (or make it available to the application a an external URL), and ensure that the Java classes required to implement the tags are on the applications classpath. The URI is simply a path on the host server, which may be relative (as an these examples) or absolute.

Author - Sumit Agarwal (sagarwal10@sapient.com)

43

Writing Tag Extensions


Processing Attributes The easiest way to parameterize tags is to pass in XML attributes. How do we make our tags handle attributes? The answer is that attributes in a TLD tag element map onto bean properties of the corresponding Tag handlers. The mapping of attributes onto Tag Handler properties is, as we might expect, handled by the JSP engine through reflection. Not only does it work with primitive types; we can pass any type to a tag handler. Whether an attribute is required or optional is specified in the TLD, as is whether attributes can take the value of a JSP expression at run time. Lets we pass a name as an attribute. We can change our simple example so that it can display any name we pass to the page as a parameter. Example: 14 A Two Tag Example to pass a name as a parameter in the request. (TwoTags.jsp, HelloTag.java, AttribHelloTag.java, twoTags.tld, web.xml).
********************************** TwoTags.jsp ********************************** <%@ taglib uri="/hello" prefix="ex"%> <%-- imports two tags named 'helloAttrib' and 'simpleHello' --%> <html><head><title>Two tags</title></head> <body> <hr> <b>SimpleHello Tag </b><ex:simpleHello /> <hr> <p><i> <ex:helloAttrib name="Sumit" /> </i></p> <hr> <%String readerName = request.getParameter("reader");%> <p> <% if (readerName != null) { %> Thank you. You told me your name.<br /> <i><ex:helloAttrib name="<%=readerName %>" /></i> <% } else { %> You're too shy to tell me your name. Try again Using the <b>reader</b> parameter in 1. Link. </br> <%}%> <hr> <br> <h3>Try these experiments.</h3> <p>1. <a href="/SimpleTag/TwoTags.jsp?reader=sumit"> Try Again.</a> This will send a paramter '?reader=Sumit' to your request.<br> Please note the URL. <p>2. <a href="/SimpleTag/TwoTags.jsp"> Try Again.</a> This will not send any parameter to your request.<br> Please note the URL. </body> </html>

Author - Sumit Agarwal (sagarwal10@sapient.com)

44

********************************** HelloTag.java ******************************** package org.tag; import java.io.IOException; import java.util.Date; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.TagSupport; public class HelloTag extends TagSupport { public int doStartTag() throws JspTagException { return EVAL_BODY_INCLUDE; } public int doEndTag() throws JspTagException { String dateString = new Date().toString(); try { pageContext.getOut().write("Hello world.<br/>"); pageContext.getOut().write( "My name is " + getClass().getName() + " and it's " + dateString + "<p/>"); } catch (IOException e) { throw new JspTagException( "Fatal error: hello tag couldn't write to JSP out"); } return EVAL_PAGE; } }//class ****************************** AttributeHelloTag.java *************************** package org.tag; import import import import java.io.IOException; java.util.Date; javax.servlet.jsp.*; javax.servlet.jsp.tagext.TagSupport;

public class AttributeHelloTag extends TagSupport { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public int doStartTag() throws JspTagException { return EVAL_BODY_INCLUDE; } public int doEndTag() throws JspTagException { String dateString = new Date().toString(); try { pageContext.getOut().write("Hello <br>" + getName() + "</b>.<br/>"); pageContext.getOut().write( "My name is " + getClass().getName() + " and it's " + dateString + "<p/>"); } catch (IOException e) { throw new JspTagException( "Fatal error: hello tag couldn't write to JSP out"); } return EVAL_PAGE; } }//class

Author - Sumit Agarwal (sagarwal10@sapient.com)

45

********************************** twoTags.tld ********************************** <?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.2</jsp-version> <short-name>examples</short-name> <description>Simple example library. Author: Sumit</description> <tag> <name>helloAttrib</name> <tag-class>org.tag.AttributeHelloTag</tag-class> <body-content>JSP</body-content> <description> Simple hello world example. Takes one attribute. </description> <attribute> <name>name</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> <tag> <name>simpleHello</name> <tag-class>org.tag.HelloTag</tag-class> <body-content>JSP</body-content> <description>Simple hello world example.</description> </tag> </taglib>

The JSP container will throw an exception if the required name attribute is not specified, and the attribute can be set with the run time value of an expression, as well as with the Static String (the value of rtexprvalue being true). The Output of this Screenshots illustrates the two cases (note the URLs).
************************************ web.xml ************************************ <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <display-name>Two Tags</display-name> <description> Tag extensions examples </description> <session-config> <session-timeout>0</session-timeout> </session-config> <taglib> <taglib-uri>/hello</taglib-uri> <taglib-location>/WEB-INF/tlds/twoTags.tld</taglib-location> </taglib> </web-app>

Author - Sumit Agarwal (sagarwal10@sapient.com)

46

In First Case, no parameters are supplied to the page then we get following output: When we specify the reader parameter we see a runtime attribute value in the given output:

Attributes are an excellent way of controlling tag behavior at run time, and are especially valuable in ensuring that tags are generic and reusable. Body Content So far we have used tags only to generate markup. We havent considered what custom tags may do to their body content (that is anything found between their start and end tags). The Scriptlets are legal for JSP contents. Lets we modify Hello.jsp our Example 13, to add some code inside of the tags, like this..
<examples:hello> <% int a = 78 %> <% int b = 81 %> This Tag Contains expressions and Scriptlets: <%=a%> * <%=b%> = <%=a*b%> </examples:hello>

Then we get the following output as a Dynamic change in run time:

Author - Sumit Agarwal (sagarwal10@sapient.com)

47

Tag Introducing Scripting Variables Two Steps are required to introducing scripting variables in a custom tags in JSP: Add one or more <variable> sub-tags to the relevant <tag> element in the TLD. Write code to add the variables to the PageContext in the tag handler itself. The variable element has the following sub-element (some are described below): name-given The Name by which the scripting variable will be accessed in the JSP. It must be a legal Java Identifier. variable-class Should be fully qualified name of the variables type. It will not be tested by the JSP engine at translation time, but used directly in code generation. For example if java.lang.Integer is specified for variable name, the JSP engine will generate a declaration such as java.lang.Integer count; in the java class representation of the JSP page. This element is optional, the default being String. scope Three types of the scope defined for variable introduced within custom tags: 1. NESTED: - if NESTED scope is specified, the variables are available to the calling JSP only within the body of the defining tag. 2. AT_BEGIN: - if AT_BEGIN scope is specified, the variables will be available to the remainder of the calling JSP after the start of the defining tag. 3. AT_END: - if AT_END scope is specified, the variable will be available to the remainder of the calling JSP after the end of the defining tag. Note: The preferred scope is NESTED.

Author - Sumit Agarwal (sagarwal10@sapient.com)

48

Example: 15 A Iteration Tag Example using the Scripting variables in the TLD. (iteration.jsp,
HelloTag.java, AttribHelloTag.java, twoTags.tld, web.xml). ************************************ iteration.jsp ****************************** <%@ taglib uri="/iteration" prefix="my"%> <%!java.util.List names = new java.util.ArrayList(); public void jspInit() { names.add("Sumit"); names.add("Priyanka"); names.add("parth"); names.add(""); }%> <html><head><title>Iteration Tag</title></head> <body> <p> <h2>Iteration Tag Example</h2> </p> <p><i> <my:iteration names="<%=names%>"> Hello <b><%=name%></b>. Your entry no. is </my:iteration> </i></p>

<%=index%> in my list.<br>

<p><i> we have finished looping, but I can now access the tag's </i>className<i> (<%=className%>)<br> and </i> date <i> (<%=date%>) scripting variables.</i> <p>You can write more HTML code here <b>Thanks:Sumit.</b></p> </body> </html>

***************************** VarHelloIterationTag.java ************************* package org.tag; import java.util.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; /** * @author sumit agarwal * */ public class VarHelloIterationTag extends BodyTagSupport { private List names; private int index = 0; public List getNames() { return names; } public void setNames(List names) { this.names = names; }

Author - Sumit Agarwal (sagarwal10@sapient.com)

49

Continue..
public int doStartTag() throws JspTagException { index = 0; setLoopVariables(); index++; return EVAL_BODY_INCLUDE; } public int doAfterBody() throws JspTagException { if (index < names.size()) { setLoopVariables(); index++; return EVAL_BODY_AGAIN; } return SKIP_BODY; } public int doEndTag() { pageContext.setAttribute("className", getClass().getName()); pageContext.setAttribute("date", new Date()); index = 0; return EVAL_PAGE; } private void setLoopVariables() { pageContext.setAttribute("name", names.get(index).toString()); pageContext.setAttribute("index", new Integer(index)); } } *************************************** web.xml ********************************* <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <display-name> Iteration Tag </display-name> <description> Iteration Tag Example </description> <taglib> <taglib-uri>/iteration</taglib-uri> <taglib-location>/WEB-INF/tlds/iteration.tld</taglib-location> </taglib> </web-app>

Author - Sumit Agarwal (sagarwal10@sapient.com)

50

************************************ iteration.tld ****************************** <?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.2</jsp-version> <short-name>examples</short-name> <description>Author: Sumit </description> <tag> <name>iteration</name> <tag-class>org.tag.VarHelloIterationTag</tag-class> <body-content>JSP</body-content> <variable> <name-given>name</name-given> <variable-class>java.lang.String</variable-class> </variable> <variable> <name-given>index</name-given> <variable-class>java.lang.Integer</variable-class> </variable> <variable> <name-given>className</name-given> <variable-class>java.lang.String</variable-class> <scope>AT_END</scope> </variable> <variable> <name-given>date</name-given> <variable-class>java.util.Date</variable-class> <scope>AT_END</scope> </variable> <attribute> <name>names</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>

Author - Sumit Agarwal (sagarwal10@sapient.com)

51

Example: 16 A Reverse Tag Example using the StringBuffers reverse( ) method. (Reverse.jsp, ReverseTag.java, Reverse.tld, web.xml).
************************************ Reverse.jsp ******************************** <%@ taglib uri="/WEB-INF/tlds/Reverse.tld" prefix="exam"%> <html> <head> <title>Reverse Custom Tag</title> </head> <body> <exam:reverse> Hi,This is the outpot of the Reverse Tag. </exam:reverse> </body> </html>

********************************** ReverseTag.java ****************************** package org.tag; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.BodyTagSupport; import javax.servlet.jsp.tagext.BodyContent; /** * @author sumit agarwal * */ public class ReverseTag extends BodyTagSupport { public int doStartTag() throws JspTagException { return EVAL_BODY_BUFFERED; // Body will not be skipped // return SKIP_BODY; //body of the tag will be skipped } public int doEndTag() throws JspTagException { BodyContent bodyContenet = getBodyContent(); if (bodyContent != null) { StringBuffer output = new StringBuffer(bodyContent.getString()); output.reverse(); try { bodyContent.getEnclosingWriter().write(output.toString()); } catch (Exception e) { throw new JspTagException("Fatal Error"); } } return EVAL_PAGE; // Rest of the page will be executed // return SKIP_PAGE; //rest of the page will be skipped } }//class

Author - Sumit Agarwal (sagarwal10@sapient.com)

52

************************************ Reverse.tld ******************************** <?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.2</jsp-version> <short-name>exam</short-name> <description> Simple example library. Author: Sumit Agarwal </description> <tag> <name>reverse</name> <tag-class>org.tag.ReverseTag</tag-class> <body-content>JSP</body-content> <description>Reverse Tag Example.</description> </tag> </taglib>

************************************** web.xml ********************************** <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <display-name>Reverse Tag</display-name> <description> Tag extension example (Tag without attributes) </description> <taglib> <taglib-uri>/reverse</taglib-uri> <taglib-location>/WEB-INF/tlds/Reverse.tld</taglib-location> </taglib> </web-app>

The Output will look like this.

Author - Sumit Agarwal (sagarwal10@sapient.com)

53

Example: 17 A Iteration Tag Example using the JDBC with the Scripting variables in the TLD.
*********************************** sql.txt ************************************* mysql> create char(3)); mysql> insert mysql> insert mysql> insert mysql> insert mysql> insert mysql> insert table employee(fname varchar(20), lname varchar(20), education va into into into into into into employee employee employee employee employee employee values('sumit','agarwal','MCA'); values('amit','agarwal','CA'); values('saurabh','agarwal','BE'); values('priyanka','agarwal','MSc'); values('monica','agarwal','MBA'); values('surbhi','agarwal','MBA');

******************************** IterationJdbc.jsp ****************************** <%@ taglib uri="/iterationjdbc" prefix="iteration"%> <html> <head> <title>Iteration Using the JDBC</title></head> <body> <font color="Black" size="5" style="Bold"> Iteration Using the JDBC </font><hr></hr> <iteration:jdbc > Name :<%=fname%> <%=lname%><br> Education :<%=education%><br> <hr></hr> </iteration:jdbc> <i>We have Finished looping, but I can now access the tag's:<br> </i>ClassName: <i> <b>(<%=className%>)</b> and <br> </i>Date: <i><b>(<%=date%>)</b>Scripting Variables.</i> <hr></hr> You Can Write More HTML Code Here ? <b>Thanks:Sumit.</b> </body> </html>

************************************* web.xml *********************************** <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <display-name>Iteration Using Jdbc</display-name> <description> Iteration Using Jdbc Example </description> <taglib> <taglib-uri>/iterationjdbc</taglib-uri> <taglib-location>/WEB-INF/tlds/IterationJdbc.tld</taglib-location> </taglib> </web-app>

Author - Sumit Agarwal (sagarwal10@sapient.com)

54

***************************** VarJDBCTag.java ************************** package org.tag; import java.sql.*; import java.io.IOException; import java.util.Date; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class VarJDBCTag extends BodyTagSupport { Connection con=null; Statement stmt=null; ResultSet rs=null; public int doStartTag()throws JspTagException{ try{ Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection ("jdbc:oracle:thin:@admin:1521:orcl","scott","tiger"); stmt = con.createStatement(); rs=stmt.executeQuery("SELECT FNAME,LNAME,EDUCATION FROM EMPLOYEE"); if(rs.next()){ setLoopVariables(); } }catch(ClassNotFoundException ce){ ce.printStackTrace(); } catch(SQLException se){ se.printStackTrace(); } catch(Exception e){ throw (new JspTagException("Jdbc Error")); } return EVAL_BODY_INCLUDE; } public int doAfterBody() throws JspTagException { try { if(rs.next()){ setLoopVariables(); return EVAL_BODY_AGAIN; } }catch(Exception e){ throw (new JspTagException("Jdbc Error")); } return SKIP_BODY; } public int doEndTag(){ pageContext.setAttribute("className",getClass().getName()); pageContext.setAttribute("date",new Date()); return EVAL_PAGE; } private void setLoopVariables() throws SQLException { pageContext.setAttribute("fname",rs.getString("FNAME")); pageContext.setAttribute("lname",rs.getString("LNAME")); pageContext.setAttribute("education",rs.getString("EDUCATION")); } }//class

Author - Sumit Agarwal (sagarwal10@sapient.com)

55

******************************* IterationJdbc.tld ******************************* <?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.2</jsp-version> <short-name>iteration</short-name> <description>Author: Sumit Agarwal </description> <tag> <name>jdbc</name> <tag-class>org.tag.VarJDBCTag</tag-class> <body-content>JSP</body-content> <variable> <name-given>fname</name-given> <variable-class>java.lang.String</variable-class> </variable> <variable> <name-given>lname</name-given> <variable-class>java.lang.String</variable-class> </variable> <variable> <name-given>education</name-given> <variable-class>java.lang.String</variable-class> </variable> <variable> <name-given>className</name-given> <variable-class>java.lang.String</variable-class> <scope>AT_END</scope> </variable> <variable> <name-given>date</name-given> <variable-class>java.util.Date</variable-class> <scope>AT_END</scope> </variable> </tag> </taglib>

Author - Sumit Agarwal (sagarwal10@sapient.com)

56

When we Run this Application we get the output show in the Next Page. This Application is used as a Report to Iterate The Data from JDBC. The output look like this:

Author - Sumit Agarwal (sagarwal10@sapient.com)

57

Anda mungkin juga menyukai