Introduction to JSTL tags for JavaWeb Details (Part 6)

Posted by PHP-Editors.com on Sun, 07 Nov 2021 17:30:42 +0100

Introduction to JSTL tags for JavaWeb Details (Part 6)

1. Overview of JSTL

1.1, What is JSTL

The full name of JSTL refers to the JavaServer Pages Standard Tag Library (JSP Standard Tag Library), which provides a series of JSP tags and can be used in various fields, such as basic input and output, process control, looping, XML file parsing, database query, internationalization and standardization of text formats, etc. It is a continuously improved open source JSP tag library.

JSTL consists of five tag libraries with different functions:

Functional scopeURIprefix
Core Label Library--FocusOracle Java Technologies | Oraclec
FormatOracle Java Technologies | Oraclefmt
functionOracle Java Technologies | Oraclefn
Database (not used)Oracle Java Technologies | Oraclesql
XML (not used)Oracle Java Technologies | Oraclex

1.2 Why use JSTL

    EL expressions are mainly used to replace expression scripts in jsp, but code scripts are not very optimized. In order to replace the traditional practice of embedding Java programs directly on the page to improve readability, maintainability and convenience, there is a JSTL tag library, which makes the whole JSP page more concise.

1.3. How to use

1) Import the jar package of the jstl tag library first

Note: Download Address

taglibs-standard-impl-1.2.5.jar
taglibs-standard-spec-1.2.5.jar(tomcat This package is also required)

2) Step 2, use the taglib directive to introduce the tag library

<!--CORE Label Library-->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!--FMT Label Library-->
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!--FUNCTIONS Label Library-->
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!--XML Label Library-->
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<!--SQL Label Library-->
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

2. Use of core label Library

    The core tag library is the core tag library of JSTL, which implements the most basic functions: process control, iteration output and so on.

The core tags are:

Labeldescribe
<c:if>Conditional expressions that construct a simple if-then structure
<c:choose>Specifies a combination boundary for multiple conditional selections, which must be used with <c:when>and <c:otherwise>tags
<c:when>Sublabel of <c:choose>to determine whether a condition is valid
<c:otherwise>Sublabels of <c:choose>followed by <c:when>labels are executed when the <c:when>label determines false
<c:forEach>Base iteration label, accepting multiple set types
<c:forTokens>Separate content based on specified delimiter and iterate output
<c:out>Output a piece of text into the browser
<c:set>Exists an object within a specified domain range
<c:remove>Used to delete data
<c:catch>Used to catch exceptions thrown by content nested within a tag body
<c:url>Construct a URL address in a JSP page
<c:import>Retrieve an absolute or relative URL and expose its content to the page
<c:redirect>Redirect to a new URL
<c:param>Used to pass parameters to pages that contain or redirect

2.1,c:if

The <c:if>tag is used for simple conditional statements.

Properties of the <c:if>tag:

attributedescribeIs it necessaryDefault value
testconditionyesnothing
varVariables used to store conditional resultsnonothing
scopeScope of var attributenopage

  Use cases:

<%@ page contentType="text/html;charset=GBK" language="java"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<title>jstl_core.jsp</title>
</head>
<body>
    <h1>jstl_core.jsp</h1>
    <%
        request.setAttribute("i", 12);
    %>
    <%--test Property must exist--%>
    <c:if test="${empty param.user}">
        <h3>Not Get user parameter</h3>
    </c:if>
    <c:if test="${i==12}">
        <h3>12==12</h3>
    </c:if>
    <%     
        String amind="Admin";   
        request.setAttribute("amind",amind); 
    %>
    <%--var Variable: used to store test Evaluation Results,scope Attribute Specification var Fields of variables--%>
    <c:if test="${requestScope.amind=='Admin'}" var="condition" scope="session">
  Match correctly
  </c:if><br>
   Get Storage Value sessionScope.condition: ${sessionScope.condition}<br>
   Get Storage Value requestScope.condition: ${requestScope.condition}
</body>
</html>

Case effect:  

2.2,c:choose,c:when,c:otherwise

    Labels <c:choose>, <c:when>, <c:otherwise> for complex judgment

  < The c:select>tag has no attributes and can be considered a parent tag, <c:when>, <c:otherwise> will be used as its child tags.

  < The c:when>tag is equivalent to an "if" statement and contains a test attribute that represents the condition that needs to be determined.

  < The c:otherwise>tag has no attributes and is equivalent to the'else'statement.

  < C:when>Label properties:

attributedescribeIs it necessaryDefault value
testconditionyesnothing

Use cases:

<%@ page contentType="text/html;charset=GBK" language="java"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<title>jstl_core.jsp</title>
</head>
<body>
    <h1>jstl_core.jsp</h1>
     <c:choose>
        <c:when test="${sex eq 'M'}">
         male
        </c:when>
        <c:when test="${sex eq 'F'}">
         female
        </c:when>
        <c:otherwise>
         Gender ambiguity
        </c:otherwise>
    </c:choose>
</body>
</html>

2.3,c:forEach,c:forTokens

    JSTL supports two iteration tags: <c:forEach> and <c:forTokens>. < The c:forTokens>tag separates the strings into an array by specifying a delimiter and iterates over them.

The <c:forEach>tag has the following properties:

attributedescribeIs it necessaryDefault value
itemsInformation to be loopednonothing
beginStarting element (0 = first element, 1 = second element)no0
endLast element (0 = first element, 1 = second element)noLast element
stepStep size for each iterationno1
varThe name of the variable that represents the current entrynonothing
varStatusVariable name representing loop statenonothing

     < The c:forTokens>tag has similar properties to the <c:forEach>tag, but <c:forTokens>has another property:

attributedescribeIs it necessaryDefault value
delimsSeparatoryesnothing

Use cases:

<%@ page contentType="text/html;charset=GBK" language="java"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.*"%>
<!DOCTYPE html>
<html>
<head>
<title>jstl_core.jsp</title>
</head>
<body>
    <h1>jstl_core.jsp</h1>
     <%--Loop from "1" to "10" and change the variable " i"Show on page--%>
     <c:forEach var="i" begin="1" end="10" step="1">
         ${i}<br />
     </c:forEach>
     
     <%--Output of prime numbers within 10--%>
     <c:forEach var="i" begin="1" step="2" end="10">
          ${i} 
     </c:forEach>
     <br>
     <%--foreach--%>
     <% 
         request.setAttribute("arr", new String[]{"18610541354","18688886666","18699998888"});
     %>
     <c:forEach items="${ requestScope.arr }" var="item">
         ${ item } <br>
     </c:forEach>
     
     <%
	     Map<String,Object> map = new HashMap<String, Object>();
	     map.put("key1", "value1");
	     map.put("key2", "value2");
	     map.put("key3", "value3");
         request.setAttribute("map", map);
     %>
     <%--ergodic Map aggregate--%>
     <c:forEach items="${ requestScope.map }" var="entry">
		${entry.key} = ${entry.value}<br>
	 </c:forEach>
</body>
</html>

Case 2:

<%@ page contentType="text/html;charset=GBK" language="java"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.*"%>
<!DOCTYPE html>
<html>
<head>
<title>jstl_core.jsp</title>
</head>
<body>
    <h1>c:forTokens</h1>
    <span>Traversal: google,runoob,taobao</span><br>
    <c:forTokens items="google,runoob,taobao" delims="," var="name">
       <c:out value="${name}"/><p>
    </c:forTokens>
</body>
</html>

Case effect:  

2.4,c:out

<c:out>Used to display data in JSP is like <%= scripting-language%>

The <c:out>tag has the following properties:

attributedescribeIs it necessaryDefault value
valueContent to be outputyesnothing
defaultDefault value of outputnoContent in Subject
escapeXmlIgnore XML special charactersnotrue

Use cases:

<%@ page contentType="text/html;charset=GBK" language="java"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<title>jstl_core.jsp</title>
</head>
<body>
    <h1>c:out</h1>
     Previous writing:
     <%out.println("hello world"); %>
     <%request.setAttribute("abc", "Hello 1");%><br>
     <%-- If the domain object has the same property name, c:out Priority is:
         pageContext>request>session>application
         It's great with two more attributes,default and escapeXml Properties.
         If we use these two attributes, we use the tag, if we don't use them EL Expression is OK
     --%>
     <c:out value="hello world"></c:out>
     <c:out value="${abc}" default="No value" escapeXml="false"></c:out> 
</body>
</html>

Case effect:

2.5,c:set

The <c:set>tag is used to assign values to variables or variable attributes in JavaBean s

The <c:set>tag has the following properties:

attributedescribeIs it necessaryDefault value
valuevalue to storenoContent of Subject
targetThe object to which the property to be modified belongsnonothing
propertyProperties to Modifynonothing
varVariables storing informationnonothing
scopeScope of var attributenoPage

Use cases:

<%@ page contentType="text/html;charset=GBK" language="java"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<title>jstl_core.jsp</title>
</head>
<body>
    <h1>c:out</h1>
     <c:set var="abc1" value="Beijing, China" scope="request"></c:set>
     <c:out value="${abc1 }"></c:out><br>
     Equivalent to:
     <% 
         request.setAttribute("abc", "Beijing, China");
     %>
     ${abc }
</body>
</html>

2.6,c:remove

The <c:remove>tag deletes variables that exist in the scope.

The <c:remove>tag has the following properties:

attributedescribeIs it necessaryDefault value
varName of variable to removeyesnothing
scopeScope to which the variable belongsnoAll Scopes

Use cases:

<%@ page contentType="text/html;charset=GBK" language="java"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<title>jstl_core.jsp</title>
</head>
<body>
    <h1>c:remove</h1>
     <c:set var="name" scope="session" value="username"/>
     <p>name Variable Value: <c:out value="${name}"/></p>
     <c:remove var="name"/>
     <p>remove name Value after variable: <c:out value="${name}"/></p>
</body>
</html>

2.7,c:catch

<c:catch>For exception capture

The <c:catch>tag has the following properties:

attributedescribeIs it necessaryDefault value
varVariables used to store error informationnoNone

Use cases:

<%@ page contentType="text/html;charset=GBK" language="java"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<title>jstl_core.jsp</title>
</head>
<body>
    <h1>c:catch</h1>
     <c:catch var="myexception">
      <%int a=9/0; %>
     </c:catch>
     <c:out value="${myexception}"></c:out>
</body>
</html>

Case effect:

2.8,c:url

The <c:url>tag formats the URL as a string and stores it in a variable.

The <c:url>tag has the following properties:

 

attributedescribeIs it necessaryDefault value
valueBase URLyesnothing
contextName of the local network applicationnoCurrent Application
varVariable name representing URLnoPrint to page
scopeScope of var attributenoPage

Use cases:

<%@ page contentType="text/html;charset=GBK" language="java"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<title>jstl_core.jsp</title>
</head>
<body>
    <h1>c:url</h1>
    <%-- Generate a string, not a link to a point,And put him in var In traversal of --%>
    <c:url value="http://www.baidu.com" var="bd"/>
    ${bd }
    <br>
    <a href="${bd }">Use Baidu Search</a>
</body>
</html>

2.9,c:import

The <c:import>tag provides all the capabilities of the <jsp:include>behavior tag, while also allowing absolute URL s.

The <c:import>tag has the following properties:

attributedescribeIs it necessaryDefault value
urlThe URL of the resource to be imported, which can be relative and absolute, and can import other host resourcesyesnothing
contextWhen accessing an external context resource using a relative path, the context specifies the name of the resource.noCurrent Application
charEncodingCharacter encoding set for introduced datanoISO-8859-1
varVariables used to store introduced textnonothing
scopeScope of var attributenopage
varReaderOptional variables to provide java.io.Reader objectsnonothing

Use cases:

<%@ page contentType="text/html;charset=GBK" language="java"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<title>jstl_core.jsp</title>
</head>
<body>
    <h1>c:import</h1>
    <c:import url="/el.jsp"></c:import>
    <hr>
    <c:import url="http://www.baidu.com" var="thisPage" charEncoding="UTF-8"/>
    <a href="${thisPage }"></a>
</body>
</html>

Case effect:

2.10,c:redirect,c:param

<c:redirect>For page redirection, this tag is equivalent to the response.setRedirect method. And supports <c:param>tags.

<c:param>Used to pass parameters to pages that contain or redirect. Can be used in <c:url>, <c:redirect>.

The <c:redirect>tag has the following properties:

attributedescribeIs it necessaryDefault value
urldestination URLyesnothing
contextNext to the name of a local network applicationnoCurrent Application

The <c:param>tag has the following properties:

attributedescribeIs it necessaryDefault value
nameName of the parameter to be set in the URLyesnothing
valueValue of parameternoBody

Use cases:

<%@ page contentType="text/html;charset=GBK" language="java"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<title>jstl_core.jsp</title>
</head>
<body>
    <h1>c:redirect</h1>
    <c:redirect url="el.jsp">
        <c:param name="userName" value="RW" />
    </c:redirect>
</body>
</html>

  Case effect:

  3. Use of fmt tag library

    The fmt tag library, which provides support for internationalization (I18N), displays different languages depending on the region of the client from which the request was made, is also known as the international tag library. It also provides methods for formatting data and dates.

The main fmt tags are:

Labeldescribe
<fmt:formatNumber>Format numbers using specified format or precision
<fmt:parseNumber>Parse a string that represents a number, currency, or percentage
<fmt:formatDate>Format date and time using specified style or pattern
<fmt:parseDate>Parse a string representing a date or time
<fmt:bundle>Bind Resources
<fmt:setLocale>Designated Area
<fmt:setBundle>Bind Resources
<fmt:timeZone>Specify time zone
<fmt:setTimeZone>Specify time zone
<fmt:message>Display resource profile information
<fmt:requestEncoding>Set character encoding for request

3.1,fmt:formatNumber

<fmt:formatNumber>Used to format numbers, percentages, currencies.

The <fmt:formatNumber>tag has the following properties:

attributedescribeIs it necessaryDefault value
valueNumber to displayyesnothing
typeNUMBER, CURRENCY, or PERCENT typenoNumber
patternSpecify a custom formatting mode for use and outputnonothing
currencyCodeCurrency code (when type="currency")noDepends on the default zone
currencySymbolCurrency symbol (when type="currency")noDepends on the default zone
groupingUsedWhether to group numbers (TRUE or FALSE)notrue
maxIntegerDigitsMaximum number of digits in integernonothing
minIntegerDigitsMinimum number of digits in integernonothing
maxFractionDigitsMaximum number of digits after decimal pointnonothing
minFractionDigitsMinimum number of digits after decimal pointnonothing
varVariables that store formatted numbersnoPrint to page
scopeScope of var attributenopage

Use cases:

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<!DOCTYPE html>
<html>
<head>
<title>jstl_core.jsp</title>
</head>
<body>
    <h1>fmt:formatNumber</h1>
    <%-- <fmt:setLocale value="zh_CN"/> 
        Note: If you want to internationalize,Then the encoding format should be set to utf-8,otherwise¥Symbol cannot be displayed
    --%>
    <c:set var="balance" value="120000.2309" />
    
    <p>Formatted Number (1): <fmt:formatNumber value="${balance}"
            type="currency"/></p>
    <p>Formatted Number (2): <fmt:formatNumber type="number"
            maxIntegerDigits="3" value="${balance}" /></p>
    <p>Formatted Number (3): <fmt:formatNumber type="number"
            pattern="#,#00.0#" value="${balance}" /></p>
    <p>Formatted Number (7): <fmt:formatNumber type="percent"
            maxIntegerDigits="3" value="${balance}" /></p>      
            
    <p>Currency in USA :
    <fmt:setLocale value="en_US"/>
    <fmt:formatNumber value="${balance}" type="currency"/></p>
</body>
</html>

Case effect:

 3.2,fmt:formatDate

The <fmt:formatDate>tag is used to format dates in different ways.

The <fmt:formatDate>tag has the following properties:

attributedescribeIs it necessaryDefault value
valueDate to displayyesnothing
typeDATE, TIME, or BOTHnodate
dateStyleFULL, LONG, MEDIUM, SHORT, or DEFAULTnodefault
timeStyleFULL, LONG, MEDIUM, SHORT, or DEFAULTnodefault
patternCustom Format Modenonothing
timeZoneTime zone showing datenoDefault time zone
varThe name of the variable that stores the formatted datenoShow on page
scopeScope to store formatted log variablesnopage

Use cases:

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<!DOCTYPE html>
<html>
<head>
<title>jstl_core.jsp</title>
</head>
<body>
    <h1>fmt:formatDate</h1>
	<c:set var="now" value="<%=new java.util.Date()%>" />
	<p>DateFormatter (1): <fmt:formatDate type="time" 
	            value="${now}" /></p>
	<p>DateFormatter (2): <fmt:formatDate type="date" 
	            value="${now}" /></p>
	<p>DateFormatter (3): <fmt:formatDate type="both" 
	            value="${now}" /></p>
	<p>DateFormatter (4): <fmt:formatDate type="both" 
	            dateStyle="short" timeStyle="short" 
	            value="${now}" /></p>
	<p>DateFormatter (5): <fmt:formatDate type="both" 
	            dateStyle="medium" timeStyle="medium" 
	            value="${now}" /></p>
	<p>DateFormatter (6): <fmt:formatDate type="both" 
	            dateStyle="long" timeStyle="long" 
	            value="${now}" /></p>
	<p>DateFormatter (7): <fmt:formatDate pattern="yyyy-MM-dd" 
	            value="${now}" /></p>
</body>
</html>

Case effect:

 

4. Use of functions label Library  

    The JSTL Functions tag library contains a series of standard functions (EL functions), most of which are generic string processing functions.

 

functiondescribe
fn:contains()Tests whether the input string contains the specified substring
fn:containsIgnoreCase()Test whether the input string contains the specified substring, case insensitive
fn:endsWith()Tests whether the input string ends with the specified suffix
fn:escapeXml()Skip characters that can be used as XML Tags
fn:indexOf()Returns the position of the specified string in the input string
fn:join()Composite elements in an array into a string and output
fn:length()Return string length
fn:replace()Replaces the position specified in the input string with the specified string and returns
fn:split()Separates strings with the specified delimiter, then forms an array of substrings and returns
fn:startsWith()Test whether the input string begins with the specified prefix
fn:substring()Returns a subset of strings
fn:substringAfter()Returns a subset of a string after a specified substring
fn:substringBefore()Returns a subset of a string before the specified substring
fn:toLowerCase()Convert characters in strings to lowercase
fn:toUpperCase()Convert characters in strings to uppercase
fn:trim()Remove trailing whitespace

Use cases:

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<!DOCTYPE html>
<html>
<head>
<title>jstl_core.jsp</title>
</head>
<body>
    <h1>fn:functions</h1>
    <p>containsIgnoreCase Function: ${fn: containsIgnoreCase ("Tomcat","CAT")}</p>
    <p>startsWith Function: ${fn: startsWith ("Tomcat","Tom")}</p>
    <p>indexOf Function: ${fn: indexOf ("Tomcat","cat")}</p>
    <p>substring Function: ${ fn: substring ("Tomcat",0,3)}</p>
</body>
</html>

Case effect:  

5. Use of xml tag library

    The JSTL XML Tag Library provides tags for creating and manipulating XML documents.

Labeldescribe
<x:out>Similar to <%=... >, but only for XPath expressions
<x:parse>Parsing XML data
<x:set>Set XPath expression
<x:if>Judges the XPath expression, executes the content in the body if it is true, otherwise skips the body
<x:forEach>Iterating nodes in an XML document
<x:choose>Parent labels for <x:when>and <x:otherwise>
<x:when>Sublabel of <x:select>for conditional judgment
<x:otherwise>Sublabel of <x:select>executed when <x:when>judges false
<x:transform>Applying XSL transformations to XML documents
<x:param>Used in conjunction with <x:transform>to set XSL stylesheets

6. Use of sql tag library

    The JSTL SQL tag library provides tags for interacting with relational databases (Oracle, MySQL, SQL Server, and so on).

Labeldescribe
<sql:setDataSource>specify data source
<sql:query>Run SQL Query Statement
<sql:update>Run SQL UPDATE statement
<sql:param>Set parameters in the SQL statement to specified values
<sql:dateParam>Set the date parameter in the SQL statement to the specified java.util.Date object value
<sql:transaction>Provide nested database behavior elements in shared database connections to run all statements as one transaction

    Since xml, and sql tag libraries aren't very useful, we'll focus on custom tags.

7. Custom Labels

7.1. Why use custom tags

    JSTL tag libraries only provide simple output and other functions, which are limited after all. There are many complex logic that may not be easily implemented with these standard tag libraries, so custom tags are required. They also have their own set of tags in Struts.

7.2. How to implement custom tags

    Let's look at the existing core tag library in the standard tag library, which has some entity classes and a c.tld.

 

  So to implement custom tags, you need to do:

1) Define a class and implement the corresponding interface;

2) Create a new tld file in the WEB-INF folder of the project;

To make a class a label class, you must implement the Jsptag interface, which is currently known as:

A) To customize a tag we need to implement the Tag or SimaapleTag interfaces;

b) Inherit the BodyTagSupport class if you want to customize a tag with a tag body and attributes

c) If you want to customize a label without a label body, inherit the TagSupport class

Depending on your needs, of course, you decide which interface or class to use.

7.3. Life cycle of custom labels

First let's look at an example:

1) Create a new MyTag1 class to implement the Tag interface

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;

public class MyTag1 implements Tag{
	/**
	 * The doEndTag() method is called when the WEB container executes the end tag of the custom tag
	 */
	@Override
	public int doEndTag() throws JspException {
		System.out.println("I called doEndTag");
		return 0;
	}
	/**
	 * The doStartTag() method is called when the WEB container executes the start tag of the custom tag
	 */
	@Override
	public int doStartTag() throws JspException {
		System.out.println("I called doStartTag");
		return 0;
	}
	
	@Override
	public Tag getParent() {
		return null;
	}
	/**
	 * When the WEB container executes a custom tag, the tag processor class resides in memory until the WEB application is stopped, and the WEB container calls the release() method
	 */
	@Override
	public void release() {
		System.out.println("I called release");
	}
	
	/**
	 * Pass pageContext object to label processor class by server call,
	 * Enables tag processor classes to communicate with JSP pages through pageContext objects
	 */
	@Override
	public void setPageContext(PageContext arg0) {
		System.out.println("I called setPageContext");
	}
	/**
	 * setPageContext()Later, if the current label does not have a parent label, null is passed in
	 */
	@Override
	public void setParent(Tag arg0) {
		System.out.println("I called setParent");
	}
}

  2) Create a new myTag.tld

<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
        version="2.1">
    <tlib-version>1.2</tlib-version>
    <short-name>my</short-name>
    <uri>http://www.mytag.com</uri>
    
    <tag>
        <name>mytag1</name>
        <tag-class>com.cn.tag.MyTag1</tag-class>
        <!--Label body contents:
            empty:Labelless body
            scriptless: Label body can contain el Expressions and JSP Action element, but cannot contain JSP Script element for
            tagdependent: Indicates that the label body is left to the label itself for parsing.
            JSP: jsp2.0 Is no longer supported, meaning it can be java Scripts, labels, or el Expression
        -->
        <body-content>empty</body-content>
    </tag>
</taglib>  

3) Create a new myjstl.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@taglib prefix="my" uri="http://www.mytag.com" %>
<!--Introduce the tag library to use uri-->
<!DOCTYPE html>
<html>
<head>
<title>myjstl.jsp</title>
</head>
<body>
    <h1>Custom Label</h1>
   <p><my:mytag1/></p>
</body>
</html>

4) Case Execution Effect

Throughout the execution process:

A) When the JSP engine encounters a custom tag, it first creates an instance object of the tag processor class;

b) Then call the setPageContext() method to pass the pageContext object to the label processor class so that it can communicate with the JSP page through the pageContext object;

c) After the setPageContext() method is executed, call the setParent() method to pass the parent label of the current label to the current processor class, or null if the current label does not have a parent label;

d) Call the doStartTag() method when the WEB container executes the start tag of the custom tag;

e) Call the doEndTag() method when the WEB container executes the end tag of the custom tag;

f) When the WEB container executes a custom tag, the tag processor class resides in memory until the WEB application is stopped, and the release() method is called by the WEB container;

7.4. Implementation of Custom Label

7.4.1, TagSupport class to implement custom labels

    TagSupport is a template class for Tag that implements pageContext, parent's getter, setter methods, and some other functions.

Use cases:

1) Create a new MyTag2 class that inherits TagSupport

package com.cn.tag;

import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class MyTag2 extends TagSupport{

	private String defaultValue;
	private String value;

	/**
	 * Property Correspondence Method
	 * @param value
	 */
    public void setValue(String value) {
        this.value = value;
    }
	
    /**
	 * Property Correspondence Method
	 * @param value
	 */
	public void setDefaultValue(String defaultValue) {
		this.defaultValue = defaultValue;
	}

	@Override
	public int doEndTag() throws JspException {
		// TODO Auto-generated method stub
		return super.doEndTag();
	}

	/**
	 * Static constants in labels:
	 * EVAL_BODY_INCLUDE: Tell the server what is in the body and put it into the output stream
	 * SKIP_BODY: Tell the server not to process body content
	 * EVAL_PAGE: Let the server continue executing the page
	 * SKIP_PAGE: Let the server not process the remaining pages
	 * EVAL_BODY_AGAIN: Let the server continue processing the body content, only the doAfterBody method can return it
	 * EVAL_BODY_BUFFERED: BodyTag Interface field, returned in doStartTag()
	 * 
	 * EVAL_BODY_INCLUDE,SKIP_BODY Normally returned by doStartTag(),
	 * And EVAL_PAPGE, SKIP_PAGE is returned by doEndTag()
	 */
	@Override
	public int doStartTag() throws JspException {
		 //Get the request object
		String str = value;
        if (value == null || "".equals(value)) {
            str = defaultValue;
        }
        JspWriter jspWriter = pageContext.getOut();
        try {
			jspWriter.write(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SKIP_BODY;
	}
	
}

2) Join myTag.tld

<tag>
        <name>mytag2</name>
        <tag-class>com.cn.tag.MyTag2</tag-class>
        <body-content>empty</body-content>
        <attribute>
            <name>value</name>
            <required>true</required>
            <!-- Whether expressions are supported -->
            <rtexprvalue>true</rtexprvalue>
        </attribute>
	    <attribute>
		    <name>defaultValue</name>
		    <required>false</required>
		    <rtexprvalue>true</rtexprvalue>
	    </attribute>
    </tag>

3) Use custom tags

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@taglib prefix="my" uri="http://www.mytag.com" %>

<!DOCTYPE html>
<html>
<head>
<title>myjstl.jsp</title>
</head>
<body>
    <h1>Custom Label</h1>
   <p><my:mytag2 value="myValue"/></p>
   <p><my:mytag2 value="" defaultValue="default"/></p>
</body>
</html>

4) Case Effect

  

  7.4.2, BodyTagSupport class to implement custom tags

    BodyTagSupport inherits the TagSupport class, implements the BodyTag interface, and can also get the contents of the label body, so if you want to customize a label that has properties of the label body, you should inherit the BodyTagSupport class.

    His life cycle: doStartTag() doInitBody() setBodyContent() doAfterBody() doEndTag()

Use cases:

1) Create a new MyTag3 class

import java.io.IOException;

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

public class MyTag3 extends BodyTagSupport{

	@Override
	public BodyContent getBodyContent() {
		return super.getBodyContent();
	}

	public int doAfterBody() throws JspException {
		// TODO Auto-generated method stub
		BodyContent content = getBodyContent();
		String str = content.getString();
		System.out.println(str);
		if(str != null){
			 String name = "";
			 if(str.startsWith("$toUpperCase(") && str.endsWith(")"))
		        {
				    String para = str.substring(13,str.length()-1);
				    if(para!=null && !"".equals(para)) {
				    	name = para.toUpperCase();
				    }
		        }
		    JspWriter out = getPreviousOut();
		try {
		    out.print(name==null?str:name);
		} catch (IOException e) {
	    	e.printStackTrace();
		 }
		}
		return SKIP_BODY;
	}

}

2)myTag.tld

<tag>
        <name>mytag3</name>
        <tag-class>com.cn.tag.MyTag3</tag-class>
        <body-content>scriptless</body-content>
    </tag>

3)myjstl.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ taglib prefix="my" uri="http://www.mytag.com" %>

<!DOCTYPE html>
<html>
<head>
<title>myjstl.jsp</title>
</head>
<body>
    <h1>Custom Label</h1>
   <%
       request.setAttribute("key", "value");
      pageContext.setAttribute("key", "value1");
   %>
   <p>${key }</p>
   <my:mytag3>$toUpperCase(${key})</my:mytag3>
   
</body>
</html>

4) Case Effect

 

Topics: Java Javascript jstl