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.


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

  <short-name>Example TLD</short-name>

Enrty in web.xml


Use in jsp page:

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

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


3) Use in jsp will be as

Output will be: Hello ank

Example of custom tag with body:

	Body Content

Then we need to modify the files as below:

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

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

2) Modify the tld and specify entry on bodycontent tag


Output will be: Body Conent Example