Thursday, 30 August 2012

JSP Custom Tags

Using JavaBeans, we can minimize lots of coding like database connectivity code or business logic from a JSP. But still we have to put some java code inside JSP.

For example consider a scenario. We created two JavaBean: 
MyBean: contains business logic like representing a row from a table.
ConnDbBean: encapsulates database connectivity and result processing logic.

and a JSP file which uses above 2 beans. Here even after using JavaBeans, we have to write java code using scriptlets in JSP file to  complete any task.

            <%-- start of scriptlet --%>
             // creating  ConnDbBean object
             ConnDbBean connBean = new  ConnDbBean();

             ArrayList dataArr =  connBean.retrieveData();

             MyBean logicBean = null;

            // iterating over ArrayList to fetch all data
            for(int i=0; i< dataArr.size(); i++){
               webBean = (MyBean)dataArr.get(i);
            <%-- end of scriptlet --%>



JSPs are built for presentation purpose only, so all the other code must be shifted elsewhere like we used JavaBeans for such purpose. Here comes the use of JSP custom tags.

JSP Custom Tags
Custom tag is a user defined component that is used to perform certain action. Now this action could be as simple as displaying “hello world” or it can be as complex as displaying records after reading it form database. It provides mechanism for encapsulating complex functionality for use in JSPs. Thus helps the non-java programmers.
We can use action <jsp:useBean> and JavaBeans to incorporate complex, encapsulated functionality in a JSP. However, with just JavaBeans, web page designers must have some knowledge to use JavaBeans in a page.
With Custom tags, it is possible for web page designers to use complex functionality without knowing any java. We can construct three types of tags :

1) Simple Tag

A simple tag has only start and End of tag. No body and attributes are specified within tag. For example:

< mytag:hello />

where, mytag – tag library prefix; hello – tag name.

2) Tag with Attributes

A tag with attributes has start and End of tag. There are attributes within tag but no enclosed body. For example:

< mytag:hello attribute = “value” />

3) Tag with Body

A tag with body has start and End of tag. There may be attributes and body is enclosed within tag. For example:

< mytag:hello optional_attributes ………… >
      some body
</ mytag:hello >

Building Custom Tags
We can use following steps to develop our own custom tag:

1) Develop the Tag Handler class

Tag Handler is a java class that is implicitly called when the associated tag is encountered in the JSP.

It must implement SimpleTag interface. However there is already a class provided (SimpleTagSupport) which implements this interface. So we can simply extend this class. For example,

public class MyTagHandler extends SimpelTagSupport {

doTag() method:-

- This is a method defined in SimpleTag interface. By default it does nothing. We need to override this to write functionality of our custom tag. This method is invoked when the end element of the tag encountered.

- JSP implicit objects (e.g. out etc) are available to tag handler class through pageContext object. pageContext object can be obtained using getJspContext() method. For example to get the reference of implicit out object, we write:

PageContext pc = (PageContext) getJspContext();
JspWriter out = pc.getOut();

2) Write Tag Library Discriptor (.tld) file

It is a XML based document and specifies information required by JSP container. It contains information such as: Tag library version, JSP version, Tag name, Tag Handler class name, Attribute names etc...

3) Deployment

For using custom tags, we need to deploy these tag handler class and .tld file at below paths:
a) Tag Handler class - myapp/WEB-INF/classes folder of web application. (myapp is any web application on server)
b) .tld file - myapp/WEB-INF/tlds folder of web application.

However there is no need to perform this step if we are using some IDE like NetBeans. These IDEs internally perform this step for us :)

4) Using Custom Tags

We have to use taglib directive in JSP to refer to the tag library. For example

<%@ taglib uri=”TLD file name” prefix=“mytag” %>

The next step is to call the tag by its name as defined in TLD. For example, if tag name is hello then we write:   < mytag:hello />

What actually happened behind the scenes?

Container calls the doTag() method of appropriate tag handler class. After that, Tag Handler will write the appropriate response back to the page.

Example : Building simple tag that displays “Hello World”
Extend Tag Handler class from SimpleTagSupport class and override doTag() method:

package custtag;

// importing required packages
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

// inheriting SimpleTagSupport class
public class HelloTagHandler extends SimpleTagSupport {

   // overriding doTag() method
   public void doTag() throws JspException {
   PageContext pageContext = (PageContext)getJspContext();
   JspWriter out = pageContext.getOut();

   try {
      out.println(" Hello World ");
   } catch ( ex) {
     throw new JspException(ex.getMessage());

TLD file: customtags.tld

<?xml version="1.0" encoding="UTF-8"?>

<taglib version="2.0"xmlns=""
xsi:schemaLocation=" webjsptaglibrary_2_0.xsd">


<!— value of uri will be used in JSP to refer this tld -->

 <!— Specifying tag name and tag class -->


<%-- taglib directive, specifying tld file name & prefix -->
<%@taglib uri="/WEB-INF/tlds/customtags.tld" prefix="mytag" %>
        <h2>Hello World Tag Example</h2>
            <mytag:welcome />

No comments:

Post a Comment