Friday, November 14, 2014

Spring MVC simple custom tag library example

Create a java file with following contents:

package com.pkm.maven.tag;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class NewDateTag extends SimpleTagSupport {
    private String prefix;
 
    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }
    
    @Override
    public void doTag() throws JspException, IOException {
        final JspWriter writer = getJspContext().getOut();
        String pattern = "dd/MM/yyyy H:m:s";
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        if (prefix != null) {
            writer.print(prefix + " ");
        }
        writer.print(format.format(new Date()));
    }
}

Create the tag library descriptor (TLD) under WEB-INF folder suppose named: "UiTabLib.tld":

<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/web-jsptaglibrary_2_0.xsd"
         version="2.0">
 
     <tlib-version>1.0</tlib-version>
     <short-name>Ui Tab Library</short-name>
     <uri>UiTabLib</uri>
  
     <tag>
         <name>newDate</name>
         <tag-class>com.pkm.maven.tag.NewDateTag</tag-class>
         <body-content>empty</body-content>
         <attribute>
             <name>prefix</name>
             <type>java.lang.String</type>
             <required>false</required>
             <rtexprvalue>true</rtexprvalue>
         </attribute>
     </tag>
</taglib>

Reference & use the tag library:

<%@taglib prefix="UiTabLib" uri="UiTabLib" %>

<p>New Date Tag Lib Output: <UiTabLib:newDate/></p>
<p>New Date Tag Lib Output: <UiTabLib:newDate prefix="Prefix"/></p>

Output would be like this:

New Date Tag Lib Output: 14/11/2014 18:25:12
New Date Tag Lib Output: Prefix 14/11/2014 18:25:12

No comments:

Post a Comment