Sunday, 10 March 2013

JSP Custom Tag Example

Q. Create a custom tag that will accept a full
name and convert into initials. For example Surendra Kumar Sharma
should be displayed as S.K. Sharma.
 Sol.
java file
package univ.myClasses;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
 * @author Navdeep
 */
public class ShortNameTagHandler extends SimpleTagSupport {
    private String name;

    @Override
    public void doTag() throws JspException {
        JspWriter out = getJspContext().getOut();
       
        try {           
            JspFragment f = getJspBody();           
            if (f != null)                 f.invoke(out);               
           
            out.print(shortName(name));
        } catch (java.io.IOException ex) {
            throw new JspException("Error in ShortNameTagHandler tag", ex);
        }
    }
    public String shortName(String name)
    {
            String sName="";
            String words[]=name.split(" ");                 
            for(String word:words)               
                sName=sName + word.substring(0, 1) + ".";        
            return sName;
    }
    public void setName(String name) {
        this.name = name;
    }
}

Tld file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">

<taglib>
  <tlibversion>1.0</tlibversion>
  <jspversion>1.1</jspversion>
  <shortname>csajsp</shortname>
  <uri>csajsp-taglib</uri>
  <info>A tag library.</info>
  <tag>
    <name>shortName</name>
    <tag-class>univ.myClasses.ShortNameTagHandler</tag-class>
    <body-content>scriptless</body-content>
    <attribute>
      <name>name</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
      <type>java.lang.String</type>
    </attribute>
  </tag>
</taglib>

jsp File

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <%@taglib uri="csajsp-taglib.tld" prefix="csajsp" %>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Test Page</title>
    </head>
    <body>
                    <csajsp:shortName name="Surendra Kumar " /> Sharma
    </body>
</html>

No comments:

Post a Comment