When a tag has a body: comparing Simple vs. Classic

Now it starts to look different from a SimpleTag. Remember, SimpleTag bodies are evaluated when (and if) you want by calling invoke() on the JspFragment that encapsulates the body. But in Classic tags, the body is evaluated in between the doStartTag() and doEndTag() methods! Both of the examples below have the exact same behavior.

The JSP that uses the tag

<%@ taglib prefix="myTags" uri="myTags" %>
<html><body>
  <myTags:simpleBody>
     This is the body
  </myTags:simpleBody>
</body></html>

A SimpleTag handler class

image with no caption

A Classic tag handler that does the same thing

image with no caption
image with no caption

Simple tag

// package and imports
public class SimpleTagTest extends SimpleTagSupport {
  public void doTag() throws JspException, IOException {
     for(int i = 0; i < 3, i++) {
       getJspBody().invoke(null);
     }
  }
}

Note

It’s easy to loop the body of a Simple tag; you just keep calling invoke() on the body, from within doTag().

Classic tag

// package and imports
public class ClassicTest extends TagSupport {

    public int doStartTag() throws JspException {
       return EVAL_BODY_INCLUDE;
}

Note

But where do you loop over the body, if the body is evaluated in between the methods instead of IN a method like doTag()?

Get Head First Servlets and JSP, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.