Author - Sumit Agarwal ([email protected]) 1 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 API’s, 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, JSP’s 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 Scores over the ASP in that: • JSPs are interpreted only once, to Java byte code and re-interpreted only when the file is modified. • JSP’s run on all the main web servers. • JSP’s provide better facilities for separation of page code and template data by mean of Java beans, EJBs and custom tag libraries. JSP ASP Platform All major Web Platforms Microsoft only Scripting Language Java JScript or VBScript Components JSP tags, JavaBeans, or EJB COM / DCOM Code Interpretation Once Each Instance
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
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.
Where the valid attributes are the following name-value pairs.
Attribute Description Default value
language Defines the scripting language to be used. This attribute exists Java in case future JSP containers support multiple languages.
extends The value is a fully qualified class name of the superclass that Omitted by The generated class, into which this JSP page is translated, default must extend.
import Comma separated list of packages or classes, with the same Omitted by
meaning as import statements in Java classes. default
session Specifies whether the page participates in an HTTP session. true
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.
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 -dependent; at
written directly through to the ServletResponse by a least 8kb
PrintWriter.
If a buffer size is specified (for example, 24kb), output is
buffered with a buffer size not less than that value.
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
isThreadSafe Define the level of thread safety implemented in the page. true
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.
info Define an informative string that can subsequently be obtained Omitted by
from the page implementation of the
Servlet.getServletInfo() method.
errorPage Defines a URL to another JSP page within the current web Omitted by
application, which is invoked if a checked or unchecked default
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.
isErrorPage Indicates if the current JSP page is intended to be another JSP false page’s 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.
contentType Define the character encoding for the JSP and the MIME type The default
for the response of the JSP Page. 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
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:
Example: 2 The next example shows how a JSP page can be included, Consider the file includeDirective2.jsp:
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:
Scripting Element 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 %>
******************************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() %>
Attribute Description Default value
uri A URI (Uniform Resource Identifier) that identifies the tag No Default
library descriptor. A tag library descriptor is used to Not specifying a
uniquely name the set of custom tags and tells the container value causes a
what to do with the specified tags. Compilation error
tagPrefix Defines the prefix string in prefix:tagname that is No Default used to define the custom tag.
The prefix jsp, jspx, java, javax, servlet, Not specifying a
sun, and sunw are reserved. 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 descriptor specified in the URI.
Example: 3 consider the simple JSP below, declaration.jsp:
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.
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.
********************************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>
**********************************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>
<% if (“scott”.equals(request.getParameter(“userName”))){ %> Hello scott. You’re logged in. <% } else { %> You’re not scott. Your user name is <%= request.getParameter(“username”)%> <% } %>
Note that code like the following example of incorrect scriptlet usages won’t work as expected:
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 object’s 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:
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 don’t 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.
<% if (“Scott”.equals(request.getParameter(“userName”))) { Hello Scott. You’re logged in. %>
******************************** 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 : {" + i + "} times" %> </body> </html>
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.
The page object is an instance of the page’s 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 client’s 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.
Example: 6 This Example Demonstrate the <jsp:useBean> Action Tag (TimeBean.java,
CurrentTimeBean.jsp) .
Attribute Description Default value
id The Case sensitive name used to identify the object instance. No Default Value 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 The scope within which the reference is available. Possible page values are “page”, “request”, “session” or “application”
class The fully qualified class name . No Default Value
beanName The name of a bean as we would supply to the instantiate() No Default
method in the java.bean .Beans class. This attribute can also be Value 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 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 bean’s class, an interface implemented attribute by it, or the bean’s 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.
****************************** 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>
******************************* 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 + "."; } } }
******************************* 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; } }
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:
Attribute Description
page The resource to include. The URL format is the same as described earlier for the
include directive.
flush 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.
Include Syntax Takes Included Parsing Type Place Content
directive <%@ include Compilation Static Parsed by Container file=“filename” %>
action <jsp:include Request- Static or Not parsed but
page = “URL” /> Processing Dynamic included in place.The
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)
Start the Tomcat web server and then request http://localhost:8080/servlets/IncludeAction.jsp you get the
following page on screen:
******************************* 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>
<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
� 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.
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).
To implement the Tag we need to define a tag handler (a java class implementing the tag’s 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.
<%@ 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>
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.
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
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 JSP’s 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 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>
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 variable’s 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.
<%@ 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 <%=index%> in my list.<br> </my:iteration> </i></p> <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; }
<?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>
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
<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>
public class VarJDBCTag extends BodyTagSupport { Connection con=null; Statement stmt=null; ResultSet rs=null; public int doStartTag()throws JspTagException{
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: