Search code examples
jspjsp-tagscustom-tags

How to create custom tags in Java Web App? How to use custom tags in JSP?


I want to create my own tag, like

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:out value="helloWorld" />

<c:forEach var="song" items="${applicationScope.songs}">
    <c:out value="song" />
</c:forEach>

Can you give an Hello World example for creating custom tags?


Solution

  • Sure no problem..

    First create a .tld file and put it under WEB-INF directory or a directory in WEB-INF directory, lets call it mytags.tld.

    And the contents of the file:

    <?xml version="1.0" encoding="UTF-8" ?>
    
    <taglib xmlns="http://java.sun.com/xml/ns/j2ee"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
            version="2.0">
    
        <description>My Tags.. My Own Tags..</description>
        <display-name>My Tags Display Name Here.</display-name>
        <tlib-version>1</tlib-version>
        <short-name>mytags</short-name>
        <uri>http://koraytugay.com/mytags</uri>
    
        <tag>
            <description>Some random tag by me</description>
            <name>myFirstTag</name>
            <tag-class>com.tugay.julyten.MyTagClass</tag-class>
            <body-content>empty</body-content>
        </tag>
    
    </taglib> 
    

    Well the most important elements here are the uri and everything inside tag element I guess..

    When the application is deployed, container will look for the .tld files so you do not need to put it in web.xml or anything. (This is valid for JSP 2.0 and later.)

    Ok now lets create MyTagClass.java in package com.tugay.julyten

    package com.tugay.julyten;
    
    import javax.servlet.jsp.JspException;
    import javax.servlet.jsp.tagext.SimpleTagSupport;
    import java.io.IOException;
    
    public class MyTagClass extends SimpleTagSupport {
        @Override
        public void doTag() throws JspException, IOException {
            getJspContext().getOut().write("You are awesome man! Awesome!!!");
        }
    }
    

    Note that our class extends SimpleTagSupport and we have overriden the method doTag() and implemented it.. It is finally time to use it in our jsp file:

    <%@ taglib prefix="mine" uri="http://koraytugay.com/mytags" %>
    <mine:myFirstTag />
    

    There you go. When you hit the jsp file, you will see:

    You are awesome man! Awesome!!!
    

    Hope this helps you getting started with custom tags..