Jsp Custom Tag

Jsp custom tag are the user defined tags, when jsp page is converted into servlet then thet will act as a operation and on the tag handler. And operation is invoked by web container.

Features:

They can be customized via attributes

Can be nested one another

Can access all the objects available to jsp page

Purpose of Custom Tags:

Replace the java scriptlet code with tags in jsp

Reusable component

Types of Tags:

1) Tags with Attributes

  e.g <mytag:test name="ank"></mytag:test>

2) Tags with Bodies

  e.g <mytag:test> Body </mytag:test>

3) Tags with Variable

  e.g <mytag:test name="ank"> Hello <%=name%></mytag:test>

Steps to create custom tags:

1) Tag Handler class

2) Tag Library Descriptor

3) Enrty of tld file in web.xml

4) Use of custom tag in jsp page

e.g test tag

  <mytag:test />

Tag Handler class:

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

  public class TestTag extends SimpleTagSupport {

    public void doTag() throws JspException, IOException {
      JspWriter out = getJspContext().getOut();
      out.println("This is custom Tag Example");
    }
  }

TLD File: abc.tld

 <taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>2.0</jsp-version>
  <short-name>Example TLD</short-name>
  <tag>
    <name>test</name>
    <tag-class>TestTag</tag-class>
    <body-content>empty</body-content>
  </tag>
 </taglib>

Enrty in web.xml

 <jsp-config>
  <taglib>
	<taglib-uri>test.tld</taglib-uri>
	<taglib-location>/WEB-INF/test.tld<taglib-location>
  </taglib>
 <jsp-config>

Use in jsp page:

 <%@ taglib prefix="mytag" uri="test.tld"%>
  <html>
   <head>
    <title>Custom tag Example</title>
   </head>
   <body>
    <mytag:test/>
   </body>
 </html>

Output will be: This is custom Tag Example

Example of custom tag with attributes:

   <mytag:test name="ank"/>

Then we need to modify the files as below:

1) In Tag handler class we can get this attribute value usin getter setter for variable name.

  
  private String name;

   public void setName(String name) {
      this.name = name;
   }
   

And then we can print out the name using out.print statement.

  
  out.print("Hello"+ name);
  

2) Modify the tld and make an enrty of attribute tag

 
    <attribute>
       <name>name</name>
    </attribute>

3) Use in jsp will be as

Output will be: Hello ank

Example of custom tag with body:

   <mytag:test>
	Body Content
   </maytag:test>

Then we need to modify the files as below:

1) In Tag handler class we need to get body content.

 BodyContent bg = getBodyContent();
 if(bg!=null)
 String body = bg.getString();
 getJspContext().getOut().println(body+ " Example");

2) Modify the tld and specify entry on bodycontent tag

 <body-content>scriptless</body-content>

Output will be: Body Conent Example