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 scope | URI | prefix |
---|---|---|
Core Label Library--Focus | Oracle Java Technologies | Oracle | c |
Format | Oracle Java Technologies | Oracle | fmt |
function | Oracle Java Technologies | Oracle | fn |
Database (not used) | Oracle Java Technologies | Oracle | sql |
XML (not used) | Oracle Java Technologies | Oracle | x |
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:
Label | describe |
---|---|
<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:
attribute | describe | Is it necessary | Default value |
---|---|---|---|
test | condition | yes | nothing |
var | Variables used to store conditional results | no | nothing |
scope | Scope of var attribute | no | page |
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:
attribute | describe | Is it necessary | Default value |
---|---|---|---|
test | condition | yes | nothing |
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:
attribute | describe | Is it necessary | Default value |
---|---|---|---|
items | Information to be looped | no | nothing |
begin | Starting element (0 = first element, 1 = second element) | no | 0 |
end | Last element (0 = first element, 1 = second element) | no | Last element |
step | Step size for each iteration | no | 1 |
var | The name of the variable that represents the current entry | no | nothing |
varStatus | Variable name representing loop state | no | nothing |
< The c:forTokens>tag has similar properties to the <c:forEach>tag, but <c:forTokens>has another property:
attribute | describe | Is it necessary | Default value |
---|---|---|---|
delims | Separator | yes | nothing |
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:
attribute | describe | Is it necessary | Default value |
---|---|---|---|
value | Content to be output | yes | nothing |
default | Default value of output | no | Content in Subject |
escapeXml | Ignore XML special characters | no | true |
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:
attribute | describe | Is it necessary | Default value |
---|---|---|---|
value | value to store | no | Content of Subject |
target | The object to which the property to be modified belongs | no | nothing |
property | Properties to Modify | no | nothing |
var | Variables storing information | no | nothing |
scope | Scope of var attribute | no | Page |
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:
attribute | describe | Is it necessary | Default value |
---|---|---|---|
var | Name of variable to remove | yes | nothing |
scope | Scope to which the variable belongs | no | All 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:
attribute | describe | Is it necessary | Default value |
---|---|---|---|
var | Variables used to store error information | no | None |
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:
attribute | describe | Is it necessary | Default value |
---|---|---|---|
value | Base URL | yes | nothing |
context | Name of the local network application | no | Current Application |
var | Variable name representing URL | no | Print to page |
scope | Scope of var attribute | no | Page |
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:
attribute | describe | Is it necessary | Default value |
---|---|---|---|
url | The URL of the resource to be imported, which can be relative and absolute, and can import other host resources | yes | nothing |
context | When accessing an external context resource using a relative path, the context specifies the name of the resource. | no | Current Application |
charEncoding | Character encoding set for introduced data | no | ISO-8859-1 |
var | Variables used to store introduced text | no | nothing |
scope | Scope of var attribute | no | page |
varReader | Optional variables to provide java.io.Reader objects | no | nothing |
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:
attribute | describe | Is it necessary | Default value |
---|---|---|---|
url | destination URL | yes | nothing |
context | Next to the name of a local network application | no | Current Application |
The <c:param>tag has the following properties:
attribute | describe | Is it necessary | Default value |
---|---|---|---|
name | Name of the parameter to be set in the URL | yes | nothing |
value | Value of parameter | no | Body |
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:
Label | describe |
---|---|
<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:
attribute | describe | Is it necessary | Default value |
---|---|---|---|
value | Number to display | yes | nothing |
type | NUMBER, CURRENCY, or PERCENT type | no | Number |
pattern | Specify a custom formatting mode for use and output | no | nothing |
currencyCode | Currency code (when type="currency") | no | Depends on the default zone |
currencySymbol | Currency symbol (when type="currency") | no | Depends on the default zone |
groupingUsed | Whether to group numbers (TRUE or FALSE) | no | true |
maxIntegerDigits | Maximum number of digits in integer | no | nothing |
minIntegerDigits | Minimum number of digits in integer | no | nothing |
maxFractionDigits | Maximum number of digits after decimal point | no | nothing |
minFractionDigits | Minimum number of digits after decimal point | no | nothing |
var | Variables that store formatted numbers | no | Print to page |
scope | Scope of var attribute | no | page |
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:
attribute | describe | Is it necessary | Default value |
---|---|---|---|
value | Date to display | yes | nothing |
type | DATE, TIME, or BOTH | no | date |
dateStyle | FULL, LONG, MEDIUM, SHORT, or DEFAULT | no | default |
timeStyle | FULL, LONG, MEDIUM, SHORT, or DEFAULT | no | default |
pattern | Custom Format Mode | no | nothing |
timeZone | Time zone showing date | no | Default time zone |
var | The name of the variable that stores the formatted date | no | Show on page |
scope | Scope to store formatted log variables | no | page |
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.
function | describe |
---|---|
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.
Label | describe |
---|---|
<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).
Label | describe |
---|---|
<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