Signup · Login
Stardeveloper.com  
Home · Tutorials · Forums · ASP.NET Newsletter Application · Web Hosting Plans · Faisal Khan's Blog · Contact
Search Stardeveloper.com
Newsletter
Enter your email address to receive full length articles at Stardeveloper:


Article Categories
.NET  .NET
  ASP (16)
  ASP.NET (41)
  ADO (16)
  ADO.NET (11)
  COM (6)
  Web Services (4)
  C# (1)
  VB.NET (3)
  IIS (2)

J2EE  J2EE
  JSP (15)
  Servlets (9)
  Web Services (1)
  EJB (4)
  JDBC (4)
  E-Commerce (1)
  J2ME (1)
  Products (1)
  Applets (1)
  Patterns (1)

Main Category  Other
  Website Maintenance (2)
Log In
UserName Or Email:

Password:

Auto-Login:

Hosted by Securewebs.com
 
Home : J2EE : JSP : Building Your first custom JSP Tag
 
Read full length articles at Stardeveloper using Twitter Follow on Twitter Facebook Facebook fan page Email Get Articles via Email RSS Get Articles via RSS Feed

Building Your first custom JSP Tag

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.
  • Tags allow easy reuse of Java code.
  • 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.*;

public class FirstTag implements Tag, Serializable {

	private PageContext pc = null;
	private Tag parent = null;
	private String name = null;

	public void setPageContext(PageContext p) {
		pc = p;
	}

	public void setParent(Tag t) {
		parent = t;
	}

	public Tag getParent() {
		return parent;
	}

	public void setName(String s) {
		name = s;
	}
	
	public String getName() {
		return name;
	}

	public int doStartTag() throws JspException {
		try {

		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;
	}

	public int doEndTag() throws JspException {
		return EVAL_PAGE;
	}

	public void release() {
		pc = null;
		parent = null;
		name = null;
	}
}

Now compile this class. FirstTag.class file will be created.

Explanation
First line is the package statement, for our FirstTag class, we put it in the com.stardeveloper.tag.test package.

package com.stardeveloper.tag.test;

Then we import the classes we will be using. For FirstTag class, we import three packages.

import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

Explanation of FirstTag Class Code
Then comes our FirstTag class declaration. Notice that we implement two interfaces; Serializable and Tag. We implement method-less interface Serializable so that our FirstTag class can be saved to the disk or serialized over the network. Serialization is not a requirement for building JSP tag classes. The next interface ( the important one ) which FirstTag class implements is the Tag interface.

Like I said on the first page, our JSP tag class will have to implement one of the two interfaces, the two interfaces that I talked about are :

  • Tag
  • 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 :

  1. setPageContext(PageContext pc)
  2. setParent(Tag parent)
  3. getParent()
  4. doStartTag()
  5. doEndTag()
  6. 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 :

  1. setName(String s)
  2. 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;

 ( 2 Remaining ) Next

Comments/Questions ( Threads: 8, Comments: 12 )
    Contains 1 or more replies by the Author of this Article.
    Contains 1 or more replies by Faisal Khan.

  1. Jsp custom Tags
  2. Jsp Custom Tags
  3. Just Thank II
  4. Just thanks
  5. Building Your first custom JSP Tag
  6. Can I use any other method in javabean which is not get/set
  7. where is web.xml role ( 1 Reply )
  8. JSP Custom Tag Exception Occure ( 3 Replies )

Post Comments/Questions

In order to post questions/comments, you must be logged-in. If you are not a member yet, then signup, otherwise login. Once you login then come back to this page and you'll see a form right here which will allow you to post comments/questions.

Please note, one of the benefits of signing up is to be notified immediately by email everytime you receive a reply to the thread you have subscribed.

 
© 1999 - 2010 Stardeveloper.com, All Rights Reserved.