jsp Creating custom tag libraries using JSP 2.0(Without java classes) A basic example of using a custom tag without any Java code


In order to create an use a custome tag,we need to follow couple of steps:

  1. Create a tag file,defining the attributes used by it and any variables which will be used by the tag

    a. The attributes need to have a name,their type and and required field with a boolean value

    b. The variables will be defined with a name along with a certain scope-

    NESTED(Available in tag body),

    AT_BEGIN(Within tag till end of scope) and

    AT_END(From end of tag till end of scope)

        <%@ attribute name="name" required="true" type="java.lang.String" description="Name of User"  %>
        <%@ attribute name="role" required="true" type="java.lang.String" description="Role of User" %>
        <%@ variable name-given="passBack" scope="AT_BEGIN"%>
        <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
        <%String backToCaller="Back to caller";%>
        <c:set var="passBack" value="Pass back successful"/>
  2. Define the entry to import tag,where tagdir will be directory containing tag file with .tag extension

    <%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>
  3. Finally use the tag,passing the required attributes,as per tag definition. Here customTag is the name of the tag file,along with prefix as defined

    <tags:customTag name="Hello Tag!!" role="I am the boss here"/>
  4. The variable set from tag can be retrieved in the caller jsp using expression language

    Hello ${passBack}