Faisal Khan: Building Your First Custom JSP Tag by
Faisal Khan: Building Your First Custom JSP Tag by
by Faisal Khan.
Overview
In this tutorial we will learn what are custom JSP tags and how to build your first JSP tag.
This tutorial assumes no prior knowledge about JSP tags.
What are JSP tags?
Well, if you know HTML, XML etc then you know what are tags. In any tag based
language ( e.g. HTML ) anything between '<' and '>' is a tag e.g. <title> is a title tag.
These HTML tags are used on the client side in the browser to format the display of data
on the user screen. Likewise in JSP we have tags between '<' and '>' and you can do just
about anything you can think of on the server-side with them e.g. <star:firsttag />.
One distinction between HTML and JSP tags is that all JSP tags obey XML tag rules.
Meaning there by, all starting tags must have an end tag e.g. <star:firsttag>
</star:firsttag>. If there is no end tag, then you should put '/' before the > tag e.g.
<star:firsttag />.
One other thing to notice is that all JSP tags have a prefix e.g. 'star' in <star:firsttag /> tag.
Like HTML and XML tags, JSP tags can have attributes e.g. <star:firsttag
attrib1="value1" attrib2="value2" /> has two attributes with two values.
Why build and use JSP tags?
Following are some of the uses which to mind :
• Tags allow separation of Java ( server-side ) and HTML ( client-side ) code. Very
important when you are building big projects and have separate people for client
and server-side development.
• You can build and pack a custom tag library with useful functions and provide it
to the end-user.
• Due to their ease of use tags can be used by non-Java programmers e.g. HTML
developers.
• Tags are easier to maintain. You don't have to edit every JSP page when you want
to make a change, just change the JSP tag and change will be manifested by all
the JSP pages.
These were only the few important uses which come to mind immediately. Only once
you learn how to build JSP tags, you'll realize how important JSP tags can be.
Is building JSP tags difficult?
Contrary to what you might be thinking, building JSP tags is as easy as building a normal
Java class file. All we have to do is to make a Java class, then either implement one of the
interfaces directly ( this is what we will do in this tutorial ) or extend one of the pre-made
Java classes and override the method/s we need. As simple as that.
Then you will have to build a simple text Tag Library Descriptor ( .TLD ) file in which
you pack the information of one or all of your tags and make it available to the
application server.
Following are the topics we cover in this tutorial :
• ϑαϖ α χλ α σ σ ωη ι χ η ιµπλ ε µ ε ν τ σ Τα γ
ιντ ε ρ φ α χ ε
• Τα γ Λιβ ρ α ρ ψ ∆εσ χ ρ ι π τ ο ρ
• ϑΣΠ πα γ ε ωη ι χ η χαλ λ σ τη ε Τα γ
• Συµ µ α ρ ψ
FirstTag.java Java Class File
Create a new .java source file and save it as 'FirstTag.java' in the /WEB-
INF/classes/com/stardeveloper/tag/test/ folder of your web application. Now copy and
paste the following code in it :
package com.stardeveloper.tag.test;
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
if(name != null) {
pc.getOut().write("Hello " + name + "!");
} else {
pc.getOut().write("You didn't enter your name");
pc.getOut().write(", what are you afraid of ?");
}
} catch(IOException e) {
throw new JspTagException("An IOException
occurred.");
}
return SKIP_BODY;
}
• BodyTag
These interfaces can be found in javax.servlet.jsp.tagext package. Tag is a simpler
interface with about six methods to implement while BodyTag extends Tag interface to
add three more methods and lot more features. Since we are building a simple JSP tag we
will be implementing Tag interface.
There are two classes provided in the javax.servlet.jsp.tagext package which provide
default implementation for the above two interfaces :
• TagSupport
• BodyTagSupport
Had we wanted we could have extended one of these classes and overridden the methods
we needed. But I thought we should implement the Tag interface directly in this tutorial
because it will aid in your learning about how it's different methods are used.
public class FirstTag implements Tag, Serializable {
The six methods which Tag interface provides and which we have to implement are :
setPageContext(PageContext pc)
setParent(Tag parent)
getParent()
doStartTag()
doEndTag()
release()
Above six methods are a must. Now if we have attributes in our tag, like we have in this
case i.e. name, then we have to add getter and setter methods for that attribute as well like
is the case with JavaBean properties :
setName(String s)
getName()
In our FirstTag class, we will be using three private variables. Two for saving reference
to PageContext and Tag objects which are provided to us by setPageContext() and
setParent() methods. And one for "name" attribute which is of type String.
private PageContext pc = null;
private Tag parent = null;
private String name = null;
if(name != null) {
pc.getOut().write("Hello " + name + "!");
} else {
pc.getOut().write("You didn't enter your name");
pc.getOut().write(", what are you afraid of ?");
}
} catch(IOException e) {
throw new JspTagException("An IOException
occurred.");
}
return SKIP_BODY;
}
doEndTag() is called when end of the tag is reached. It returns EVAL_PAGE so that rest
of the page is read by the server.
public int doEndTag() throws JspException {
return EVAL_PAGE;
}
In the last we code the release() method. This method is called by the JSP page when all
the methods of the tag class have been called and it is time to free resources. In this
method you should free the resources you may have accumulated during the execution of
other methods of the class.
public void release() {
pc = null;
parent = null;
name = null;
}
}
Tag Library Descriptor
A Tag Library Descriptor ( or simply TLD ) file is a simple XML file which provides
details about your JSP tag/s. Create a new DemoTags.tld file in the /WEB-INF/tlds
folder. Copy and paste the following text in it :
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>DemoTags</shortname>
<uri>http://www.stardeveloper.com</uri>
<info>Demo Tags Library</info>
<tag>
<name>firsttag</name>
<tagclass>com.stardeveloper.tag.test.FirstTag</tagclass>
<bodycontent>empty</bodycontent>
<info>Your first JSP Tag</info>
<attribute>
<name>name</name>
<required>false</required>
</attribute>
</tag>
</taglib>
Explanation
Everything is packed between <taglib> and </taglib> tags. First five sub-tags under the
<taglib> tag are general tags for providing info about the tag library as a whole. They are
not specific to any tag.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
tlibversion tag tells about the current version of tag library. Since this is the first time we
built this demo tag library, I put 1.0 in it.
<tlibversion>1.0</tlibversion>
jspversion tells the application server what version of JSP this tag library uses. There are
currently three versions of JSP, 1.0, 1.1 and future version 1.2. Our JSP tag FirstTag uses
JSP version 1.1.
<jspversion>1.1</jspversion>
A simple short name for the tag library.
<shortname>DemoTags</shortname>
uri tag doesn't do much job in the current version of JSP.
<uri>http://www.stardeveloper.com</uri>
A short text about the use of this tag library.
<info>Demo Tags Library</info>
Now comes individual tag description between the <tag> and </tag> tag.
<tag>
<name>firsttag</name>
<tagclass>com.stardeveloper.tag.test.FirstTag</tagclass>
<bodycontent>empty</bodycontent>
<info>Your first JSP Tag</info>
<attribute>
<name>name</name>
<required>false</required>
</attribute>
</tag>
name is the short name you will be using in the JSP page after the prefix e.g. firsttag in
the <star:firsttag /> tag.
tagclass should contain the complete path to the JSP tag class.
bodycontent should contain one of the three values; tagdependent, JSP and empty. Since
there is body content in our tag so we select empty.
Optional info tag.
Then attribute tag describes each attribute separately. name is the name of the attribute, in
our case it is "name". required can be true or false. We chose false so this tag can be used
without entering value for the "name" attribute.
We have finished building the FirstTag.class and DemoTags.tld files. Let's now build the
JSP page which calls this tag.
FirstTag.jsp JSP page
Create a new JSP page under the folder where you can run JSP pages. For this demo, I'll
assume /web/jsp folder. Save this .jsp page as FirstTag.jsp and copy / paste the following
code in it :
<html>
<head>
<title>Your first JSP tag : FirstTag</title>
<style>
p, b { font-family:Tahoma,Sans-Serif; font-size:10pt; }
b { font-weight:bold; }
</style>
</head>
<body>
<p align="center">
<em><u>Your first JSP tag : FirstTag</u></em></p>
</body>
</html>
Explanation
We use the taglib directive to tell the application server we will be using a JSP tag in our
JSP page. There are two attributes to taglib directive; uri and prefix. We set the uri
attribute to the local address of DemoTags.tld TLD file. prefix attribute asks about the
prefix we are going to use for this tag library, I chose "star".
<%@ taglib uri="/WEB-INF/tlds/DemoTags.tld" prefix="star" %>
Then we use the tag twice in the JSP page, first time we enter our name in the name
attribute for the tag. Second time we don't enter anything in the name attribute.
<p>Name entered : <star:firsttag name="Faisal Khan" /></p>
Summary
We learned that JSP tags are a powerful way to re-use code. To create a custom JSP tag,
you should first build a Java class which should either implement Tag or BodyTag
interfaces present in the javax.servlet.jsp.tagext package or extend TagSupport or
BodyTagSupport classes present in the same package.
In this tutorial we implemented the Tag interface directly and also added an attribute
"name" for our tag. To use attributes in your tags, you should provide a private variable
with the same name as that of the attribute in your Java class, and then provide getter and
setter methods for all of the attributes.
The order with which JSP page calls the different of Tag interface is as follows :
• setPageContext()
• setParent()
• setAttribute1(value1)
• setAttribute2(value2)
• doStartTag()
• doEndTag()
• release()
You should release any resources you may have accumulated in your Java class file in the
release() method of the Tag interface.
We also learned to package one or more tags together, we make use of Tag Library
Descriptor ( .TLD ) file. A .TLD file contains descriptions for one or more tags along
with their attributes.
In the end we built the FirstTag.jsp JSP page which called the firsttag. To call a custom
built JSP tag in your JSP pages, you should make use of taglib directive and set it's uri
attribute to the local address of this tag's .TLD file. And set the prefix attribute for taglib
directive to any name you like.
Well this is it for this time. Hope you liked the tutorial and learned how to create JSP
tags.
Overview
In this article we will learn how exceptional events can occur in a JSP page and how to
catch these exceptional events to display a more useful message to the user.
What are Exceptions ?
Exceptions mean exceptional events and as we all know exceptional events can occur
anywhere in a program e.g. you are trying to connect to a database and the database
server is down, now you wouldn't have expected this to happen ;).
How to catch Exceptions ?
You can catch exceptions in a JSP page like you would do in other Java classes. Simply
put the code which can throw an exception/s between a try..catch block.
<%
try {
// Code which can throw can exception
} catch(Exception e) {
// Exception handler code here
}
%>
There is yet another useful way of catching exceptions in JSP pages. You can specify
error page in the 'page' directive. Then if any exception is thrown, the control will be
transferred to that error page where you can display a useful message to the user about
what happened and also inform your sysadmin about this exception depending obviously
on how important it may be.
In this article we will explore this error page method of exception handling in JSP pages.
Building Demo Pages
To demonstrate the run-time exception handling feature of JSP pages, we will build three
pages.
• FormHandler.jsp - A JSP Page which receives this value and prints it on the user
screen.
</body>
</html>
Explanation
Form.html page simply displays a single input field Form to the user to enter his age in
years. The name of input field where user will enter his/her age is "age". We will use this
input field name "age" in the FormHandler.jsp page to receive it's value.
ii. FormHandler.jsp
Create new FormHandler.jsp page. Copy and paste the following code in it :
<%@ page errorPage="ExceptionHandler.jsp" %>
<html>
<head>
<style>
body, p { font-family:Tahoma; font-size:10pt; }
</style>
</head>
<body>
age = Integer.parseInt(request.getParameter("age"));
%>
<p><a href="Form.html">Back</a>.</p>
</body>
</html>
Explanation
Code above is rather simple. Notice the first line, the page directive. It specifies an
errorPage ExceptionHandler.jsp, our exception handler JSP page.
<%@ page errorPage="ExceptionHandler.jsp" %>
Then we declare an int variable "age". Then using the static method of Integer class we
parse the entered value using Integer.parseInt() method. The value is retrieved using
request.getParameter() method. The argument to request.getParameter() is the name of
Form field whose value we want to retrieve.
<%
int age;
age = Integer.parseInt(request.getParameter("age"));
%>
If all goes well and user entered an int ( e.g. 12345 ) value in the input field then we
display that value back to the user.
<p>Your age is : <%= age %> years.</p>
Now things can go wrong and exceptional events can occur. For example, if user didn't
enter a value and what if user entered his name ( e.g. "Faisal Khan"), of String type
instead of an integer ?.
These things will be handled by the ExceptionHandler.jsp JSP page.
iii. ExceptionHandler.jsp
Create a new ExceptionHandler.jsp page. Copy and paste the following code in it :
<%@ page isErrorPage="true" import="java.io.*" %>
<html>
<head>
<title>Exceptional Even Occurred!</title>
<style>
body, p { font-family:Tahoma; font-size:10pt; padding-left:30; }
pre { font-size:8pt; }
</style>
</head>
<body>
<%
out.println("<!--");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
out.print(sw);
sw.close();
pw.close();
out.println("-->");
%>
</body>
</html>
Explanation
To make a JSP page exception handler ( i.e. errorPage ), you have to specify isErrorPage
attribute in the page directive at the top and set it's value to true.
<%@ page isErrorPage="true" %>
When a JSP page has been declared an errorPage, it is made available an object with
name of "exception" of type java.lang.Throwable. We use different methods of this
exception object to display useful information to the user.
<font color="red">
<%= exception.toString() %><br>
</font>
We can put the stack trace information for debugging inside HTML <!-- --> comment
tags. So that user only sees a useful message and the sysadmin, developers can see the
whole story.
<%
out.println("<!--");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
out.print(sw);
sw.close();
pw.close();
out.println("-->");
%>
To use the PrintWriter and StringWriter classes you'll have to import java.io.* package in
your JSP page by changing the page directive at the top to :
<%@ page isErrorPage="true" import="java.io.*" %>
Running the Demo Pages
Place Form.html, FormHandler.jsp and ExceptionHandler.jsp pages in a place where your
application server ( e.g. Tomcat, Orion etc ) can find them. Never put your JSP pages in
the /WEB-INF/ folder.
I placed these three pages in the /web/jsp/ folder so the path to these pages on my system
will be http://localhost:8080/web/jsp/Form.html and so on. Notice that on my system
application server is running on 8080 port. You should change the port number to the one
where your application server is running.
Enter your age e.g. 24, in the input field and press the submit button. You should see
FormHandler.jsp page giving you a response like following :
Your age is : 24 years.
Now try again. This time don't enter any value or simply enter a non-integer value e.g.
your name, and press the submit button. Now instead of FormHandler.jsp page showing
you your age, the control will be internally passed to ExceptionHandler.jsp page which
will show an exception message in red color :
java.lang.NumberFormatException:
To see the complete stack trace view the source of the page. On Internet Explorer, click
View -> Source. On the source page you will see complete exception stack trace written.
Although our demo application worked and you learned about specifying error pages e.g.
ExceptionHandler.jsp, in your normal JSP pages e.g. FormHandler.jsp, there is still a
catch. The exception message that was given to the user i.e.
java.lang.NumberFormatException, is not very useful, is it? To give a more useful
message keep reading.
Improved FormHandler.jsp page
Remove the FormHandler code in FormHandler.jsp page and add the following one :
<%
int age;
try {
age = Integer.parseInt(request.getParameter("age"));
} catch (NumberFormatException e) {
throw new JspException("Please enter a valid integer
value!");
}
%>
Explanation
This time we catch the NumberFormatException locally and throw a new JspException
with our own exception message. JspException is a JSP special exception class which
extends java.lang.Exception. So all we had to do is to give our own message to the
JspException class. Now lets see what will happen this time.
We will just have to edit one single line in ExceptionHandler.jsp for it to work.
Improved ExceptionHandler.jsp
Simply change the exception handler code with this one :
<font color="red">
<%= exception.getMessage() %><br>
</font>
That's it. Now view the Form.html page again and don't enter any value and press the
submit button. This time you will not see "java.lang.NumberFormatException", rather the
message will be :
Please enter a valid integer value!
And like before you can see the complete stack trace by viewing the source for the
FormHandler.jsp page in your browser.
Summary
In this article we learned about exception handling feature of JSP pages. We learned that
to make a JSP an error page, we have to set the isErrorPage attribute in the page directive
at the top to true. Now this JSP page will be an error page and it will be made available as
java.lang.Throwable object with name "exception". We can use methods of "exception"
object e.g. exception.getMessage(), exception.toString(), exception.printStackTrace(), to
display useful information to the user.
To make exceptions from other JSP pages to go to the error page above, we have to set
the errorPage attribute in the page directive at the top to the location of our JSP error
page e.g. errorPage="ExceptionHandler.jsp".