Custom Tags

  • JSP 1.1 support creation of custom tags that enables seperation of business logic from the content presentation.

  • The Structure of a custom tag in JSP, like those in XML and HTML, contain the start/end tag and a body.
  • Advantages of Using Custom tags:-
  • They can reduce or eliminate scriptlets in your JSP application.
  • They are reusable.
  • They can improve the productivity of non-programmer , content-developers,by allowing them to perform tasks that cannot be done with HTML.
Types of Custom Tag:-
  1. <br> No Body , No Attribute
  2. <hr size="3" > No Body with Attribute
  3. <b>THIS IS TEXT </b> With body No Attribute
  4. <Font face="Arial" size="10"> THIS IS TEXT </font> With body with Attribute.
custom.tld
 <taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>2.0</jsp-version>
  <short-name>Example </short-name>
  <tag>
    <name>Hello</name>
    <tag-class>com.learn.JSPExample</tag-class>
    <body-content>scriptless</body-content>
    <attribute>
       <name>message</name>
    </attribute>
  </tag>
</taglib>
			
JSPExample.java
package com.learn;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;

public class JSPExample extends SimpleTagSupport {

   private String message;

   public void setMessage(String msg) {
      this.message = msg;
   }

   StringWriter sw = new StringWriter();

   public void doTag()
      throws JspException, IOException
    {
       if (message != null) {
          /* Use message from attribute */
          JspWriter out = getJspContext().getOut();
          out.println( message );
       }
       else {
          /* use message from the body */
          getJspBody().invoke(sw);
          getJspContext().getOut().println(sw.toString());
       }
   }

}
			
msg.jsp
<%@ taglib prefix="ex" uri="/WEB-INF/custom.tld"%>
<html>
  <head>
    <title>A sample custom tag</title>
  </head>
  <body>
    <ex:Hello message="This is Simple custom tag" />
  </body>