Tuesday, October 12, 2010

JSP- Custom Tag- Body with Attributes


JSP- Custom Tag- Body with Attributes

Introduction:

From Previous post, we have understood how to create custom body tag. From this post, we will learn how to create custom tag with body and attributes. If we create attribute, we will add attribute name when we create tag Handler class.

Procedure:

Step 1:
            Create Project CustomTagProject.

Step 2:
            Create TLD file named as ABody.tld


Successfully Abody.tld file created.
 
Step 3:
            Create Tag handler Class named as Abody

1). Put Tag Handler name i.e. class name as Abody

2). BodyTagSupport in Tag Support Class to Extend


























Click Next

1). Select TLD file.
2). Body Content as JSP
3) To add attribute.

               Click New

                        Add New Attribute window will open.

                        Where you give Attribute name as username

                        And select Attribute Type as java.lang.String

            Select required attribute checkbox


Successfully Tag Handler class file created.
 
Step 4:

            Made some changes in ABody.java

package javaclass;

import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class ABody extends BodyTagSupport
{
    private String username;

    public String getUsername()
    {
        return username;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    public int doAfterBody()throws JspException
    {
        try
        {
            BodyContent bc=getBodyContent();
            String body=bc.getString();
            JspWriter out=bc.getEnclosingWriter();
            out.println(getUsername().toUpperCase());
            out.println(body.toUpperCase());
        }
        catch(Exception e)
        {

        }
        return SKIP_BODY;
    }
}
Step 5:

            Create jsp file named as ABody.jsp


Step 6:

Run the jsp file named ABody

Step 7:

Output

Structure of the CustomTagProject



































No comments:

Post a Comment