Thursday, 6 December 2012

Custom tag using JSP without body

JSP custom tag without body

steps

first create a folder named as st in WEB-INF\classes directory

Then create java file named as HellTag.java  inside st

paste the following on  HellTag.java file

package st;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;

public class HellTag extends TagSupport
{
    public int doStartTag()
    {
        try{
            JspWriter js=pageContext.getOut();
            js.print("Hello");
        }
        catch(Exception ex)
        {
            System.out.println(ex.getMessage());
        }
        return SKIP_BODY;
    }
}

compile the HelloTag.java file by following manner
javac HellTag.java -classpath "C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\jsp-api.jar"

Then create st.tld file inside the WEB-INF directory

then paste following to st.tld file

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
        PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
    "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>2.0</jsp-version>
  <short-name>st</short-name>
   
     <tag>
     <name>Hello</name>
     <tag-class>st.HellTag</tag-class>
     <body-content>empty</body-content>
  </tag>   
 
</taglib>


Then create a folder named as tlds inside the WEB-INF folder
then copy the st.tld file to tlds folder.

then create jsp file as follow in  anywhere and run that by appache.

<%@page language="java" contentType="text/html" %>

<%@ taglib uri="/WEB-INF/tlds/st.tld" prefix="Hell"%>

<html>
    <body>
        <Hell:Hello/>
    </body>
       
</html>


Output 

custom tag in JSP
jsp custom tag

 

No comments:

Post a Comment