Launch your tech mastery with us—your coding journey starts now!
Course Content
Advanced Java

Steps for creating custom tags in JSP:

  1. Start with a new Web Application and within the source package select new package—-give name mypkg.
  2. Right click on mypkg->Java Class and write the code.

package mypkg;

import javax.servlet.jsp.tagext.*;

import javax.servlet.jsp.*;

import java.io.*;

public class HelloTag extends SimpleTagSupport {

StringWriter sw = new StringWriter();

private String message;

  public void doTag() throws JspException, IOException {

            if (message != null) {

          /* Use message from attribute */

          JspWriter out = getJspContext().getOut();

          out.println( message );

       }

       else {

          /* use message from the body */

          getJspBody().invoke(sw);

          getJspContext().getOut().println(sw.toString());

       }

        }

    public void setMessage(String msg) {

      message = msg;

   }}

 

  1. Right click on WEB-INF->Other->Web->Tag Library descriptor->give name mytag and write the code.

<taglib>

  <tlib-version>1.0</tlib-version>

  <jsp-version>2.0</jsp-version>

  <short-name>Example TLD</short-name>

    <tag>

           <name>Hello</name>

       <tag-class>mypkg.HelloTag</tag-class> 

       <body-content>scriptless</body-content>

     <attribute>

       <name>message</name>  

      <required>false</required>        

    </attribute>

   </tag></taglib>

 

  1. Goto index.jsp & type this code

<%@page contentType=”text/html” pageEncoding=”UTF-8″%>

<!DOCTYPE html>

<html>

    <head>

        <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>

        <title>JSP Page</title>

    </head>

    <body>

        <%@taglib prefix=”ty” uri=”WEB-INF/tlds/mytag.tld”  %>

        <ty:Hello message=”hurrahh”>oooppsps</ty:Hello>

    </body>

</html>

 

  1. Run the JSP file.