Create your own tag: a custom tag body : Tag « JSP « Java

Create your own tag: a custom tag body

   <!-- this must be added to the web application's web.xml -->


// create File:java2s.tld in the /WEB-INF/
<!DOCTYPE taglib
  PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"

    <!-- a tab library descriptor -->
<taglib xmlns="">
  <short-name>Java2s Simple Tags</short-name>

  <!-- this tag manipulates its body content by converting it to upper case

//compile the following code into WEB-INF\classes\com\java2s
package com.java2s;

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class BodyContentTag extends BodyTagSupport
  private int iterations, howMany;

  public void setHowMany(int i)
    this.howMany = i;

  public void setBodyContent(BodyContent bc)
    System.out.println("BodyContent = '" + bc.getString() + "'");
  public int doAfterBody()
      BodyContent bodyContent = super.getBodyContent();
      String      bodyString  = bodyContent.getString();
      JspWriter   out         = bodyContent.getEnclosingWriter();

      if ( iterations % 2 == 0 ) 

      bodyContent.clear(); // empty buffer for next evaluation
    catch (IOException e) 
      System.out.println("Error in BodyContentTag.doAfterBody()" + e.getMessage());
    } // end of catch

    int retValue = SKIP_BODY;
    if ( iterations < howMany ) 
      retValue = EVAL_BODY_AGAIN;
    return retValue;
// start comcat and load the bodyContent.jsp in browser
<%@ taglib uri="/java2s" prefix="java2s" %>

    <title>A custom tag: body content</title>
    This page uses a custom tag manipulates its body content.
    Here is its output:
      <java2s:bodyContentTag howMany="3">


Related examples in the same category

1.Your own simple JSP tag
2.A custom tag that has neither attributes nor body content.
3.A custom tag: empty with attributes
4.A custom tag: scripting variable
5.Write your own tag
6.Logo Tag
7.A custom tag: empty
8.Tag lifecycle with Attribute
9.A custom tag: iteration
10.JSP Simple Tags
11.JSP tag: advanced tagsJSP tag: advanced tags
12.JSP classic tagsJSP classic tags
13.JSP Tag Libraries and JSTLJSP Tag Libraries and JSTL
14.JSP Directives: HTML tag