Post Reply 
Thread Rating:
  • 1 Votes - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Building Your Own Custom JSP Tag Library
02-06-2011, 09:04 AM
Post: #1
Building Your Own Custom JSP Tag Library
We can build Custom Tags in Jsp by using Tag File.A tag file is a special kind of custom action that is developed much like a JSP page. Unlike JSP pages, tag files can be invoked from within JSP pages in the same way Java Standard Tag Library (JSTL) tags are used. Tag files, for instance, can be passed parameters to use, and they can expose values to the calling JSP page, and invoke fragments of JSP code.

To understand more about Tag file ,we will explain with simple example of how a tag file is created and invoked in a JSP page.

The tag example here will display a message and the current date in the format day/month/year. Its output will look something like the following:

Today date is: 10 / 11 / 2008
The JSP page that invokes the tag file will appear as follows:

<%@ taglib prefix=/"testjsp/" tagdir=/"/WEB-INF/tags/" % >

First, the taglib JSP directive is used to define the tags that will be used on this page. In this case, the prefix used is testjsp . The taglib directive also identifies the folder in which the tag files can be found: /WEB-ING/tags, using the tagdir attribute. For instance, if your application were on your computer as C:\sample\, the tagdir attribute used above would be the directory located at C:\sample\WEB-INF\tags.

The invocation of the tag is like any other custom tag invocation you have seen throughout this book: <testjsp:todaydates/ > .

To create the tag itself, a file called todaydates.tag is placed in the /WEB-INF/tags folder of the Web application. All tag files must be placed in this directory or a directory below it. The content of todaydates.tag is as follows:

<%@ tag body-content="empty" % >
<jsp:useBean id=\"today\" scope=\"page\" class=\"java.util.Date\"/ >

Today date is: ${} / ${today.month} / ${today.year + 1900}
As you can see, the content of the tag file is very simple. The tag directive is first defined in order to declare some properties of the tag. Various attributes can be used in this directive, but for this example only the body-content attribute is required. This and other attributes are defined later in this chapter.

After the tag directive, the logic of the tag itself begins. jsp:useBean is used to define a new instance of the java.util.Date

This demo shows the simplicity with which tag files can be created and invoked.Output is as show above

object. By default, this native Java object is instantiated with the current system date.

Advantages of using Tag files:

Code reuse
Hiding complexity
Separation of concerns
Flexible packaging
Find all posts by this user
Quote this message in a reply
Post Reply 

Forum Jump:

Send your comments, Suggestions or Queries regarding this site at

Copyright © 2010 All Rights Reserved