JSP SimpleTagSupport Example


JSP SimpleTagSupport Example

SimpleTagSupport
The SimpleTagSupport class is a utility class intended to be used as the base class for new simple tag handlers. The SimpleTagSupport class implements the SimpleTag interface and adds additional convenience methods including getter methods for the properties in SimpleTag. I am going to follow below steps to create a simple JSP Tag

1. Create Tag handler class

package com.pretech;

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

public class PretechSimpleTag extends SimpleTagSupport {
    public void doTag() throws JspException, IOException {
        JspWriter out = getJspContext().getOut();
        out.print("Hello world From tag library");

    }
}

2.Create Tld file and placed in WEB-INF directory

<?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/web-jsptaglibrary_2_0.xsd" version="2.0">
<tlib-version>1.0</tlib-version>
<short-name>pretech-taglib</short-name>
<tag>
<description>Hello world</description>
<name>helloworld</name>
<tag-class>com.pretech.PretechSimpleTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>

3. Create Jsp file with taglib directive and tag (PretechTag.jsp)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
  <%@ taglib uri="/WEB-INF/pretechtld.tld"
 prefix="pretech" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>
          Pretech Tag Library example
        </title>
      </head>
      <body>
        <pretech:helloworld/>
      </body>
    </html>

4. Deploy application and run it Output

clip_image002

 

1 comment:

  1. Great example but I want to see more examples about
    how to create taglibs without use code java.

    SimpleTag is like a Servlet Of course not work same ! I need somothing more better

    ReplyDelete

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts