JSP Custom Tag Simple Getting Started

  • 2021-10-13 08:19:19
  • OfStack

In the official document of sun, there is the following paragraph.

Official document statement


public interface SimpleTag
extends JspTag
Interface for defining Simple Tag Handlers.
Simple Tag Handlers differ from Classic Tag Handlers in that instead of supporting doStartTag() and doEndTag(), the SimpleTag interface provides a simple doTag() method, which is called once and only once for any given tag invocation. All tag logic, iteration, body evaluations, etc. are to be performed in this single method. Thus, simple tag handlers have the equivalent power of BodyTag, but with a much simpler lifecycle and interface.

To support body content, the setJspBody() method is provided. The container invokes the setJspBody() method with a JspFragment object encapsulating the body of the tag. The tag handler implementation can call invoke() on that fragment to evaluate the body as many times as it needs.

A SimpleTag handler must have a public no-args constructor. Most SimpleTag handlers should extend SimpleTagSupport.

Life cycle and call flow

The following is a non-normative, brief overview of the SimpleTag lifecycle. Refer to the JSP Specification for details.

A new tag handler instance is created each time by the container by calling the provided zero-args constructor. Unlike classic tag handlers, simple tag handlers are never cached and reused by the JSP container.
The setJspContext() and setParent() methods are called by the container. The setParent() method is only called if the element is nested within another tag invocation.
The setters for each attribute defined for this tag are called by the container.
If a body exists, the setJspBody() method is called by the container to set the body of this tag, as a JspFragment. If the action element is empty in the page, this method is not called at all.
The doTag() method is called by the container. All tag logic, iteration, body evaluations, etc. occur in this method.
The doTag() method returns and all variables are synchronized.

Simple label use small case

Must know must know: Simple label is also a label, so the declaration process is also Tag 1, which is also 3 steps.

1. Build an implementation class that inherits SimpleTag class and override doTag method
2. Strict declaration in tld file
3. Namespace and label prefix declaration of taglib in jsp page, and then call custom simple label

Step 1: Create an implementation class:


package web.simpletag;
import java.io.IOException;
import java.io.StringWriter;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.SkipPageException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;


/**
 *  Control whether the tag body is executed 
 * @author Summer
 *
 */
public class BodyController extends SimpleTagSupport {
  static{
    /*
     *  The overall implementation process of simple labels is as follows: 
     * 1. Browser direction web The server sends the request, and then web Server call servlet ( jsp ) 
     * 2.complier The interpreter initializes by calling the setJspContext Method, setting the pageContext Object is passed in 
     * 3. Then look at the parent tag of this tag, which is setParent Method 
     * 4. Then there is the call doTag Method, right? But you know doTag Internally, it will use JspFragment Object, so you must get it first, so it should be called setJspBody(JspFragment jspBody) Method 
     * 5. Finally, call the doTag  Method to execute the associated code logic 
     */
  }

  /**
   *  Simple tags can use this 1 Methods to implement all business logic 
   */
  @Override
  public void doTag() throws JspException, IOException {
    // An object representing the tag body 
    JspFragment fragment = this.getJspBody();
    //fragment.invoke(null); It refers to who to write the contents of the label to, null Represents the browser 


    //1. Modify the contents of the tag body 
//   fragment.invoke(null);


    //2. Control the repeated output of tag body content 
//   for(int i=1;i<=5;i++){
//     fragment.invoke(null);// Set to null Output to the browser by default 
//   }


    //3. Modify the contents of the tag body 
    PageContext context = (PageContext) fragment.getJspContext();
    StringWriter writer = new StringWriter();
    fragment.invoke(writer);
    String content = writer.getBuffer().toString();

    this.getJspContext().getOut().write(content.toUpperCase());

    //4. Control jsp Whether the page is executed or not, you only need to master 1 One principle is enough 
    /*
     * SkipPageException - If the page that (either directly or indirectly) invoked this 
     * tag is to cease evaluation. A Simple Tag Handler generated from a tag
     * file must throw this exception if an invoked Classic Tag Handler
     *  returned SKIP_PAGE or if an invoked Simple Tag Handler threw
     *  SkipPageException or if an invoked Jsp Fragment threw a 
     *  SkipPageException.
     */
//   throw new SkipPageException();
  }


}

Configure related constraint items in tld file:


<?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 http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
  version="2.0">

  <description>JSTL 1.1 XML library</description>
  <display-name>JSTL XML</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>x</short-name>
  <uri>/simplesummer</uri>


  <!--  Custom tags of simple tags that control the content of tag body  -->
  <tag>
    <name>BodyController</name>
    <tag-class>web.simpletag.BodyController</tag-class>
    <body-content>scriptless</body-content>
  </tag>
</taglib>

Step 3: Declare in the jsp page and call:


<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<%@taglib uri="/simplesummer" prefix="summer"%>
<!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=UTF-8">
<title> Use SimpleTag A test page implemented by the interface to control whether the contents of the tag body are executed or not </title>
</head>
<body>
  <summer:BodyController>Summer</summer:BodyController>


</body>
</html>

Summary:
Simple tags can replace the BodyTag interface to do the same, but they are simpler and more portable
The simple label lifeCycle has clear logic and clear calling rules
The manipulation of tag body can be completed by using correlation flow object maniplate

The above is the whole content of this paper, hoping to help everyone's study.


Related articles: