A Guide to the JSTL Library – JSTL图书馆指南

最后修改: 2018年 4月 12日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

JavaServer Pages Tag Library (JSTL) is a set of tags that can be used for implementing some common operations such as looping, conditional formatting, and others.

JavaServer Pages标签库(JSTL)是一组标签,可用于实现一些常见的操作,如循环、条件格式化和其他。

In this tutorial, we’ll be discussing how to setup JSTL and how to use its numerous tags.

在本教程中,我们将讨论如何设置JSTL以及如何使用其众多标签。

2. Setup

2.设置

To enable JSTL features, we’d have to add the library to our project. For a Maven project, we add the dependency in pom.xml file:

要启用JSTL功能,我们必须在项目中添加该库。对于Maven项目,我们在pom.xml文件中添加该依赖项。

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

With the library added to our project, the final setup will be to add the core JSTL tag and any other tags’ namespace file to our JSP using the taglib directive like this:

随着库被添加到我们的项目中,最后的设置将是使用taglib指令将核心JSTL标签和任何其他标签的命名空间文件添加到我们的JSP中,像这样。

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Next, we’ll take a look at these tags which are broadly grouped into five categories.

接下来,我们将看一下这些标签,它们大致分为五类。

3. Core Tags

3.核心标签

JSTL core tag library contains tags for performing basic operations such as printing values, variables declaration, exception handling, performing iterations, and declaring conditional statements among others.

JSTL核心标签库包含用于执行基本操作的标签,如打印值、变量声明、异常处理、执行迭代和声明条件语句等等。

Let’s have a look at core tags.

让我们看一下核心标签。

3.1. The <c:out> Tag

3.1.<c:out>标签

<c:out> is used for displaying values contained in variables or the result of an implicit expression.

<c:out>用于显示变量中包含的值或隐式表达式的结果。

It has three attributes: value, default, and escapeXML. The escapeXML attribute outputs raw XML tags contained in the value attribute or its enclosure.

它有三个属性。value、default和escapeXML。 escapeXML属性输出包含在value属性或其外壳中的原始XML标签。

An example of <c:out> tag will be:

<c:out>标签的一个例子将是。

<c:out value="${pageTitle}"/>

3.2. The <c:set> Tag

3.2.<c:set>标签

The <c:set> tag is used for declaring scoped variables in JSP. We can also declare the name of the variable and its value in the var and value attributes respectively.

<c:set>标签用于声明JSP中的范围变量。我们也可以在varvalue属性中分别声明变量的名称和它的值。

An example will be of the form:

一个例子将是这样的。

<c:set value="JSTL Core Tags Example" var="pageTitle"/>

3.3. The <c:remove> Tag

3.3.<c:remove>标签

The <c:remove> tag removes scoped variables which is equivalent to assigning null to a variable. It takes var and scope attribute with scope having a default value of all scopes.

<c:remove>标签删除作用域变量,这相当于将null分配给一个变量。它需要varscope属性,scope有一个所有作用域的默认值。

Below, we show an example usage of <c:remove> tag:

下面,我们展示了一个使用<c:remove> tag的例子。

<c:remove var="pageTitle"/>

3.4. The <c:catch> Tag

3.4.<c:catch>标签

The <c:catch> tag catches any exception thrown within its enclosure. If the exception is thrown, it’s value is stored in the var attribute of this tag.

<c:catch>标签捕捉任何在其外壳内抛出的异常。如果异常被抛出,它的值将被存储在这个标签的var属性中。

Typical usage could look like:

典型的用法可能看起来像。

<c:catch var ="exceptionThrown">
    <% int x = Integer.valueOf("a");%>
</c:catch>

And to check if the exception is thrown, we use the <c:if> tag as shown below:

为了检查异常是否被抛出,我们使用<c:if>标签,如下所示。

<c:if test = "${exceptionThrown != null}">
    <p>The exception is : ${exceptionThrown} <br />
      There is an exception: ${exceptionThrown.message}
    </p>
</c:if>

3.5. The <c:if> Tag

3.5.<c:if>标签

The <c:if> is a conditional tag that displays or executes it’s enclosed scriptlets only when its test attribute evaluates to true. The result of the evaluation can be stored in its var attribute.

<c:if>是一个条件标签,只有当它的test属性评估为真时才会显示或执行它所包围的小脚本。评估的结果可以存储在其var属性中。

3.6. <c:choose>, <c:when> and <c:otherwise> Tags

3.6.<c:choice>, <c:when><c:otherwise> 标签

The <c:choose> is a parent tag that is used in performing switch-like or if-else expressions. It has two subtags; <c:when> and <c:otherwise> which represent if/else-if and else respectively.

<c:choose>是一个父标签,用于执行类似开关或if-else表达。它有两个子标签;<c:when><c:otherwise>,分别代表if/else-if和else。

<c:when> takes a test attribute which holds the expression to be evaluated. Below, we show an example usage of these tags:

<c:when>需要一个test属性,该属性持有要被评估的表达。下面,我们展示了这些标签的一个使用实例。

<c:set value="<%= Calendar.getInstance().get(Calendar.SECOND)%>" var="seconds"/>
<c:choose>
    <c:when test="${seconds le 30 }">
        <c:out value="${seconds} is less than 30"/>
    </c:when>
    <c:when test="${seconds eq 30 }">
        <c:out value="${seconds} is equal to 30"/>
    </c:when>
    <c:otherwise>
        <c:out value="${seconds} is greater than 30"/>
    </c:otherwise>
</c:choose>

3.7. The <c:import> Tag

3.7.<c:import>标签

The <c:import> tag handles fetching and exposing content from absolute or relative URLs.

<c:import>标签处理从绝对或相对的URL中获取和公开内容。

We can use the url and var attributes to hold the URL, and the content fetched from the URL respectively. For example, we could import contents from a URL by:

我们可以使用urlvar属性来分别保存URL和从URL中获取的内容。例如,我们可以通过以下方式从一个URL导入内容。

<c:import var = "data" url = "http://www.example.com"/>

3.8. The <c:forEach> Tag

3.8.<c:forEach>标签

The <c:forEach> tag is similar to Java’s for, while or do-while syntax. The items attribute holds the list of items to be iterated over, while begin and end attributes hold the starting and ending index respectively (zero indexing).

<c:forEach>标签类似于Java的for、while或do-while语法。items属性持有要迭代的项目列表,而beginend属性分别持有起始和结束索引(零索引)。

<c:forEach> tag also has a step attribute that controls the size of index increment after each iteration. Below, we show an example usage:

<c:forEach>标签也有一个step属性,控制每次迭代后索引增量的大小。下面,我们展示一个使用实例。

<c:forEach var = "i" items="1,4,5,6,7,8,9">
    Item <c:out value = "No. ${i}"/><p>
</c:forEach>

3.9. The <c:forTokens> Tag

3.9.<c:forTokens>标签

The <c:forTokens> tag is used for splitting a String into tokens and iterating through them.

<c:forTokens>标签用于将一个String分割成tokens,并对它们进行迭代。

Similar to <c:forEach> tag, it has an items attribute and an additional delim attribute which is the delimiter for the String like this:

<c:forEach>标签类似,它有一个items属性和一个额外的delim属性,是String的分隔符,像这样。

<c:forTokens 
  items = "Patrick:Wilson:Ibrahima:Chris" 
  delims = ":" var = "name">
    <c:out value = "Name: ${name}"/><p>
</c:forTokens>

3.10. <c:url> and <c:param> Tags

3.10.<c:url><c:param> 标签

The <c:url> tag is useful for formatting a URL with proper request encoding. the formatted URL is stored in the var attribute.

<c:url>标签对于用适当的请求编码来格式化一个URL很有用。格式化的URL被存储在var属性中。

<c:url> tag also has a <c:param> subtag which is used for specifying URL parameters. We show an example below:

<c:url>标签也有一个<c:param>子标签,用于指定URL参数。我们在下面展示一个例子。

<c:url value = "/core_tags" var = "myURL">
    <c:param name = "parameter_1" value = "1234"/>
    <c:param name = "parameter_2" value = "abcd"/>
</c:url>

3.11. The <c:redirect> Tag

3.11.<c:redirect>标签

The <c:redirect> tag performs a URL rewrite and redirects the user to the page specified in its url attribute. A typical use case will look like this:

<c:redirect>标签执行URL重写,将用户重定向到其url属性中指定的页面。一个典型的用例是这样的。

<c:redirect url="/core_tags"/>

4. Formatting Tags

4.格式化标签

JSTL formatting tag library provides a convenient way for formatting text, numbers, dates, times and other variables for better display.

JSTL格式化标签库为文本、数字、日期、时间和其他变量的格式化提供了一种方便的方式,以便更好地显示。

JSTL formatting tags can also be used to enhance the internationalization of a website.

JSTL格式化标签也可用于加强网站的国际化。

Before using these formatting tags, we’ve to add the taglib to our JSP:

在使用这些格式化标签之前,我们必须在我们的JSP中加入taglib。

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

Let’s identify the various formatting tags and how they can be used.

让我们来确定各种格式化标签以及如何使用它们。

4.1. The <fmt:formatDate> Tag

4.1.<fmt:formatDate> 标签

The <fmt:formatDate> tag is useful in formatting dates or time. The value attribute holds the date to be formatted, and the type attribute takes one of three values; date, time or both.

<fmt:formatDate>标签在格式化日期或时间时非常有用。value属性保存要格式化的日期,而type属性取三个值之一;日期、时间或两者

<fmt:formatDate> also has a pattern attribute where we can specify the desired formatting pattern. Below is an example of one of the patterns:

<fmt:formatDate>也有一个pattern属性,我们可以指定所需的格式化模式。下面是其中一个模式的例子。

<c:set var="now" value="<%= new java.util.Date()%>"/>
<fmt:formatDate type="time" value="${now}"/>

4.2. The <fmt:parseDate> Tag

4.2.<fmt:parseDate> 标签

The <fmt:parseDate> tag is similar to <fmt:formatDate> tag.

<fmt:parseDate>标签与<fmt:formatDate> 标签类似。

The difference is that with <fmt:parseDate> tag we can specify the formatting pattern that the underlying date parser should expect the date value to be in.

区别在于,通过<fmt:parseDate>标签,我们可以指定底层日期分析器应该期待日期值的格式化模式。

We can parse dates:

我们可以解析日期。

<c:set var="today" value="28-03-2018"/>
<fmt:parseDate value="${today}" var="parsedDate" pattern="dd-MM-yyyy"/>

4.3. The <fmt:formatNumber> Tag

4.3.<fmt:formatNumber> 标签

The <fmt:formatNumber> tag handles rendering of numbers in a specific pattern or precision which can be one of number, currency or percentage as specified in its type attribute. An example usage of <fmt:formatNumber> would be:

<fmt:formatNumber>标签处理以特定的模式或精度呈现数字,可以是在其type属性中指定的number, currency 或 percentage之一。<fmt:formatNumber>的一个用法示例是。

<c:set var="fee" value="35050.1067"/>
<fmt:formatNumber value="${fee}" type="currency"/>

4.4. The <fmt:parseNumber> Tag

4.4.<fmt:parseNumber> 标签

The <fmt:parseNumber> tag is similar to <fmt:formatNumber> tag. The difference is that with <fmt:parseNumber> tag we can specify the formatting pattern that the underlying number parser should expect the number to be in.

<fmt:parseNumber>标签与<fmt:formatNumber>标签类似。不同的是,使用<fmt:parseNumber>标签,我们可以指定底层数字分析器应该期待的数字的格式化模式。

We could use this like:

我们可以像这样使用。

<fmt:parseNumber var="i" type="number" value="${fee}"/>

4.5. The <fmt:bundle> Tag

4.5.<fmt:bundle>标签

The <fmt:bundle> tag is a parent tag for <fmt:message> tag. <fmt:bundle> makes the bundle specified in its basename attribute to the enclosed <fmt:message> tags.

<fmt:bundle>标签是<fmt:message>标签的一个父标签。<fmt:bundle>使其basename属性中指定的bundle成为被包围的<fmt:message>标签。

<fmt:bundle> tag is useful for enabling internationalization as we can specify locale-specific objects. Typical usage will be of the form:

<fmt:bundle>标签对于实现国际化非常有用,因为我们可以指定特定于本地的对象。典型的用法是这样的。

<fmt:bundle basename="com.baeldung.jstl.bundles.CustomMessage" prefix="verb.">
    <fmt:message key="go"/><br/>
    <fmt:message key="come"/><br/>
    <fmt:message key="sit"/><br/>
    <fmt:message key="stand"/><br/>
</fmt:bundle>

4.6. The <fmt:setBundle> Tag

4.6.<fmt:setBundle> 标签

The <fmt:setBundle> tag is used for loading a resource bundle within JSP and making it available through the entire page. The loaded resource bundle is stored in the var attribute of the <fmt:setBundle> tag. We can set bundle by:

<fmt:setBundle>标签用于在JSP中加载一个资源包,并使其在整个页面中可用。加载的资源包被存储在var标签的<fmt:setBundle>属性中。我们可以通过以下方式设置bundle。

<fmt:setBundle basename="com.baeldung.jstl.bundles.CustomMessage" var="lang"/>

4.7. The <fmt:setLocale> Tag

4.7.<fmt:setLocale> 标签

The <fmt:setLocale> tag is used to set the locale for the sections in JSP placed after it’s declaration. Typically we will set this by:

<fmt:setLocale>标签用于设置JSP中放在它的声明之后的部分的locale。通常情况下,我们将通过以下方式设置。

<fmt:setLocale value="fr_FR"/>

fr_FR represents the locale which is French in this case.

fr_FR代表当地语言,在本例中为法语。

4.8. The <fmt:timeZone> Tag

4.8.<fmt:timeZone> 标签

The <fmt:timeZone> tag is a parent tag that specifies the time zone to be used by any time formatting or parsing actions by tags in its enclosure.

<fmt:timeZone>标签是一个父标签,它指定了要被其外壳中的标签的任何时间格式化或解析动作所使用的时区。

This time zone parameter is supplied by its value attribute. An example usage is shown below:

这个时区参数是由其value属性提供的。下面是一个使用实例。

<fmt:timeZone value="${zone}">
    <fmt:formatDate value="${now}" timeZone="${zn}" 
      type="both"/>
</fmt:timeZone>

4.9. The <fmt:setTimeZone> Tag

4.9.<fmt:setTimeZone> 标签

The <fmt:setTimeZone> tag can be used to copy the time zone specified in its value attribute to a scoped variable specified in its var attribute. We define this by:

<fmt:setTimeZone>标签可用于将其value属性中指定的时区复制到其var属性中指定的范围变量。我们通过以下方式来定义它。

<fmt:setTimeZone value="GMT+9"/>

4.10. The <fmt:message> Tag

4.10.<fmt:message>标签

The <fmt:message> tag is used to display internationalization message. The unique identifier for the message to be retrieved should be passed to its key attribute.

<fmt:message>标签用于显示国际化的消息。要检索的消息的唯一标识符应传递给其key属性。

A specific bundle to lookup the message which can also be specified through the bundle attribute.

一个特定的捆绑包来查找消息,也可以通过bundle属性来指定。

This may look like this:

这可能看起来像这样。

<fmt:setBundle basename = "com.baeldung.jstl.bundles.CustomMessage" var = "lang"/>
<fmt:message key="verb.go" bundle="${lang}"/>

4.11. The <fmt:requestEncoding> Tag

4.11.<fmt:requestEncoding> 标签

The <fmt:requestEncoding> tag is useful in specifying the encoding type for forms with an action type of post.

<fmt:requestEncoding>标签在为动作类型为post的表单指定编码类型时非常有用。

The name of the character encoding to use is supplied through the key attribute of the <fmt:requestEncoding> tag.

要使用的字符编码的名称是通过key属性的<fmt:requestEncoding>标签提供的。

Let’s see an example below:

让我们看看下面的一个例子。

<fmt:requestEncoding value = "UTF-8" />

5. XML Tags

5.XML标签

JSTL XML tag library provides convenient ways for interacting with XML data within a JSP.

JSTL XML标签库为在JSP中与XML数据进行交互提供了方便的方法。

To be able to access these XML tags, we’d add the tag library to our JSP by:

为了能够访问这些XML标签,我们要在我们的JSP中加入标签库。

<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

Let’s look at the different tags in the JSTL XML tags library.

我们来看看JSTL XML标签库中的不同标签。

5.1. The <x:out> Tag

5.1.<x:out>标签

The <x:out> tag is similar to <%= %> scriptlet tag in JSP but <x:out> is specifically used for XPath expressions.

<x:out>标签类似于JSP中的<%=%> scriptlet标签,但<x:out>是专门用于XPath表达式。

<x:out> tag has a select and escapeXML attributes used for specifying the XPath expression to evaluate a String and to enable escaping of special XML characters respectively.

<x:out>标签有一个selectescapeXML属性,分别用于指定XPath表达式来评估String和启用特殊XML字符的转义。

A simple example is:

一个简单的例子是。

<x:out select="$output/items/item[1]/name"/>

$output in the above refers to a preloaded XSL file.

$output在上面指的是一个预装的XSL文件。

5.2. The <x:parse> Tag

5.2.<x:parse>标签

The <x:parse> tag is used for parsing the XML data specified in its xml or doc attribute or enclosure. A typical example would be:

<x:parse>标签用于解析在其xmldoc属性或包围中指定的XML数据。一个典型的例子是。

<x:parse xml="${xmltext}" var="output"/>

5.3. The <x:set> Tag

5.3.<x:set>标签

The <x:set> tag sets the variable specified in its var attribute to the evaluated XPath expression passed to its select attribute. A typical example would be:

<x:set>标签将其var属性中指定的变量设置为传递给其select属性的已评估XPath表达式。一个典型的例子是。

<x:set var="fragment" select="$output//item"/>

5.4. The <x:if> Tag

5.4.<x:if>标签

The <x:if> tag processes its body if the XPath expression supplied to its select attribute evaluates to true.

<x:if>标签在其select属性提供的XPath表达式评估为真时,会处理其主体。

The result of the evaluation can be stored in its var attribute.

评估的结果可以存储在其var属性中。

A simple use case will look like:

一个简单的用例将看起来像。

<x:if select="$output//item">
    Document has at least one <item> element.
</x:if>

5.5. The <x:forEach> Tag

5.5.<x:forEach>标签

The <x:forEach> tag is used for looping over nodes in an XML document. The XML document is supplied through <x:forEach> tag’s select attribute.

<x:forEach>标签用于在一个XML文档中的节点上循环。XML文档是通过<x:forEach>标签的select属性提供。

Just like the <c:forEach> core tag, <x:forEach> tag has begin, end and step attributes.

就像<c:forEach>核心标签一样,<x:forEach>标签有begin、endstep属性。

Thus, we’d have:

因此,我们会有。

<ul class="items">
    <x:forEach select="$output/items/item/name" var="item">
        <li>Item Name: <x:out select="$item"/></li>
    </x:forEach>
</ul>

5.6. <x:choose>, <x:when> and <x:otherwise> Tags

5.6.<x:choice>, <x:when><x:otherwise> 标签

The <x:choose> tag is a parent tag that is used in performing switch-like or if/else-if/else expressions and has no attributes but encloses <x:when> and <x:otherwise> tags.

<x:choice>标签是一个父标签,用于执行类似开关或if/else-if/else表达式,没有属性,但包围着<x:when><x:otherwise>标签。

<x:when> tag is similar if/else-if and takes a select attribute which holds the expression to be evaluated.

<x:when>tag类似于if/else-if,并接受一个select属性,该属性持有要被评估的表达式。

<x:otherwise> tag is similar to else/default clause and has no attribute.

<x:otherwise>标签与else/default子句类似,没有属性。

Below, we show a sample use case:

下面,我们展示一个用例。

<x:choose>
    <x:when select="$output//item/category = 'Sneakers'">
        Item category is Sneakers
    </x:when>
    <x:when select="$output//item/category = 'Heels'">
        Item category is Heels
    </x:when>
    <x:otherwise>
       Unknown category.
    </x:otherwise>
</x:choose>

5.7. <x:transform> and <x:param> Tags

5.7.<x:transform><x:param> 标签

The <x:transform> tag transforms an XML document within JSP by applying an eXtensible Stylesheet Language (XSL) to it.

<x:transform>标签在JSP中通过应用可扩展样式表语言(XSL)来转换一个XML文档。

The XML document or String to be transformed is supplied to the doc attribute while the XSL to be applied is passed to the xslt attribute of the <x:transform> tag.

要转换的XML文档或String被提供给doc属性,而要应用的XSL被传递给xslt属性的<x:transform> tag。

<x:param> tag is a subtag of <x:transform> tag and it is used to set a parameter in the transformation stylesheet.

<x:param>标签是<x:transform>标签的一个子标签,它被用来在转换样式表中设置一个参数。

A simple use case will be of the form:

一个简单的用例将是这样的形式。

<c:import url="/items_xml" var="xslt"/>
<x:transform xml="${xmltext}" xslt="${xslt}">
    <x:param name="bgColor" value="blue"/>
</x:transform>

6. SQL Tags

6.SQL标签

JSTL SQL tag library provides tags for performing relational database operations.

JSTL SQL标签库提供了用于执行关系数据库操作的标签s。

To enable JSTL SQL tags, we add the taglib to our JSP:

为了启用JSTL SQL标签,我们将taglib添加到我们的JSP中。

<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

JSTL SQL tags support different databases including MySQL, Oracle and Microsoft SQL Server.

JSTL SQL标签支持不同的数据库,包括MySQL、Oracle和Microsoft SQL Server。

Next, we’ll look at the different SQL tags available.

接下来,我们来看看有哪些不同的SQL标签。

6.1. The <sql:setDataSource> Tag

6.1.<sql:setDataSource>标签

The <sql:setDataSource> tag is used for defining the JDBC configuration variables.

<sql:setDataSource>标签用于定义JDBC配置变量。

These configuration variables are held in the driver, url, user, password and dataSource attributes of the <sql:setDataSource> tag as shown below:

这些配置变量被保存在driver, url, user, password dataSource 属性中,如下图所示:<sql:setDataSource>标签。

<sql:setDataSource var="dataSource" driver="com.mysql.cj.jdbc.Driver"
  url="jdbc:mysql://localhost/test" user="root" password=""/>

In the above, the var attribute holds a value that identifies the associated database.

在上面,var属性持有一个标识相关数据库的值。

6.2. The <sql:query> Tag

6.2.<sql:query>标签

The <sql:query> tag is used to execute an SQL SELECT statement with the result stored in a scoped variable defined in its var attribute. Typically, we’d define this as:

<sql:query>标签用于执行一个SQL SELECT语句,其结果存储在其var属性中定义的范围内变量。通常情况下,我们会将其定义为。

<sql:query dataSource="${dataSource}" var="result">
    SELECT * from USERS;
</sql:query>

<sql:query> tag’s sql attribute holds the SQL command to be executed. Other attributes include maxRows, startRow, and dataSource.

<sql:query>标签的sql属性持有要执行的SQL命令。其他属性包括maxRowsstartRowdataSource

6.3. The <sql:update> Tag

6.3.<sql:update>标签

The <sql:update> tag is similar to <sql:query> tag but executes only SQL INSERT, UPDATE or DELETE operations which do not require a return value.

<sql:update>标签与<sql:query>标签类似,但只执行不需要返回值的SQL INSERT、UPDATE或DELETE操作。

An example usage would be:

一个例子的用法是。

<sql:update dataSource="${dataSource}" var="count">
    INSERT INTO USERS(first_name, last_name, email) VALUES
      ('Grace', 'Adams', 'gracea@domain.com');
</sql:update>

<sql:update> tag’s var attribute holds the number of rows that were affected by the SQL statement specified in its sql attribute.

<sql:update>标签的var属性持有被其sql属性中指定的SQL语句影响的行数。

6.4. The <sql:param> Tag

6.4.<sql:param>标签

The <sql:param> tag is a sub tag that can be used within <sql:query> or <sql:update> tag to supply a value for a value placeholder in the sql statement as this:

<sql:param>标签是一个子标签,可以在<sql:query><sql:update>标签中使用,为sql语句中的值占位符提供一个值。

<sql:update dataSource = "${dataSource}" var = "count">
    DELETE FROM USERS WHERE email = ?
    <sql:param value = "gracea@domain.com" />
</sql:update>

<sql:param> tag has a single attribute; value which holds the value to be supplied.

<sql:param>标签有一个单一的属性;value,持有要提供的值。

6.5. The <sql:dateParam> Tag

6.5.<sql:dateParam> 标签

The <sql:dateParam> tag is used within <sql:query> or <sql:update> tag to supply a date and time value for a value placeholder in the sql statement.

<sql:dateParam>标签被用于<sql:query><sql:update>标签中,为sql语句中的值占位符提供一个日期和时间值。

We can define this in our JSP like this:

我们可以在我们的JSP中这样定义它。

<sql:update dataSource = "${dataSource}" var = "count">
    UPDATE Users SET registered = ? WHERE email = ?
    <sql:dateParam value = "<%=registered%>" type = "DATE" />
    <sql:param value = "<%=email%>" />
</sql:update>

Like the <sql:param> tag, <sql:dateParam> tag has a value attribute with an additional type attribute whose value can be one of date, time or timestamp (date and time).

<sql:param>标签一样,<sql:dateParam>标签有一个value属性和一个额外的type属性,其值可以是date,timetimestamp(日期和时间)之一。

6.6. The <sql:transaction> Tag

6.6.<sql:transaction>标签

The <sql:transaction> tag is used to create JDBC transaction-like operation by grouping <sql:query> and <sql:update> tags together like this:

<sql:transaction>标签通过将<sql:query><sql:update>标签组合在一起,用来创建类似JDBC的事务操作。

<sql:transaction dataSource = "${dataSource}">
    <sql:update var = "count">
        UPDATE Users SET first_name = 'Patrick-Ellis' WHERE
          email='patrick@baeldung.com'
    </sql:update>
    <sql:update var = "count">
        UPDATE Users SET last_name = 'Nelson' WHERE 
          email ='patrick@baeldung.com'
    </sql:update>
    <sql:update var = "count">
        INSERT INTO Users(first_name, last_name, email) 
          VALUES ('Grace', 'Adams', 'gracea@domain.com');
    </sql:update>
</sql:transaction>

<sql:transaction> tag ensures that all database operations are processed successfully (committed) or all fail gracefully (rolled back) if an error occurs in any of the operations.

<sql:transaction>标签确保所有的数据库操作都被成功处理(提交),或者在任何操作发生错误时都能优雅地失败(回滚)。

7. JSTL Functions

7.JSTL功能

JSTL methods are utilities for data manipulation within JSP. While some functions take different data types, most of them are dedicated for String manipulation.

JSTL方法是在JSP中进行数据操作的实用工具。虽然有些函数接受不同的数据类型,但它们中的大多数是专门用于String操作的。

To enable JSTL methods in JSP, we’d add the taglib to our page:

为了在JSP中启用JSTL方法,我们会在我们的页面中添加taglib。

<%@ taglib prefix = "fn"
  uri = "http://java.sun.com/jsp/jstl/functions" %>

Let’s look at these functions and how to use them.

让我们来看看这些功能和如何使用它们。

7.1. fn:contains() and fn:containsIgnoreCase()

7.1.fn:contains()fn:containsIgnoreCase()

The fn:contains() method evaluates a String to check if it contains a given substring like this:

fn:contains()方法评估一个字符串以检查它是否包含一个给定的子串,像这样。

<c:set var = "string1" value = "This is first string"/>
<c:if test = "${fn:contains(string1, 'first')}">
    <p>Found 'first' in string<p>
</c:if>

The fn:contains() function takes two String arguments; the first is the source String and the second argument is the substring. It returns a boolean depending on the result of the evaluation.

fn:contains() 函数需要两个String参数;第一个是源String,第二个参数是子串。它根据评估的结果返回一个布尔值。

The fn:containsIgnoreCase() function is a case-insensitive variant of the fn:contains() method and can be used like this:

fn:containsIgnoreCase()函数是fn:contains()方法的不区分大小写的变体,可以像这样使用。

<c:if test = "${fn:containsIgnoreCase(string1, 'first')}">
    <p>Found 'first' string<p>
</c:if>
<c:if test = "${fn:containsIgnoreCase(string1, 'FIRST')}">
    <p>Found 'FIRST' string<p>
</c:if>

7.3. The fn:endsWith() Function

7.3.fn:endersWith() 函数

The fn:endsWith() function evaluates a String to check if its suffix matches another substring. It takes two arguments; the first argument is the String whose suffix is to be tested while the second argument is the tested suffix.

fn:endersWith()函数评估一个String以检查其后缀是否与另一个子串相匹配。它需要两个参数;第一个参数是后缀要被测试的String,第二个参数是被测试的后缀。

We can define this like:

我们可以这样定义。

<c:if test = "${fn:endsWith(string1, 'string')}">
    <p>String ends with 'string'<p>
</c:if>

7.4. The fn:escapeXml() Function

7.4.fn:escapeXml() 功能

The fn:escapeXML() function is used to escape XML markup in the input String like this:

fn:escapeXML()函数被用来转义输入String中的XML标记,就像这样。

<p>${fn:escapeXml(string1)}</p>

7.5. The fn:indexOf() Function

7.5.fn:indexOf() 功能

The fn:indexOf() function looks through a String and returns the index of the first occurrence of a given substring.

fn:indexOf()函数查看一个字符串,并返回给定子串的第一次出现的索引。

It takes two arguments; the first is the source String and the second argument is the substring to match and return the first occurrence.

它需要两个参数;第一个是源String,第二个参数是要匹配的子串,并返回第一个出现的子串。

fn:indexOf() function returns an integer and can be used like:

fn:indexOf()函数返回一个整数,可以像这样使用。

<p>Index: ${fn:indexOf(string1, "first")}</p>

7.6. The fn:join() Function

7.6.fn:join() 功能

The fn:join() function concatenates all elements of an array into a single String and can be used like this:

fn:join()函数将一个数组的所有元素连接成一个单一的String,可以像这样使用。

<c:set var = "string3" value = "${fn:split(string1, ' ')}" />
<c:set var = "string4" value = "${fn:join(string3, '-')}" />

7.7. The fn:length() Function

7.7.fn:length() 函数

The fn:length() function returns the number of elements in the given collection or the number of characters in the given String.

fn:length()函数返回给定集合中的元素数或给定String.中的字符数。

The fn:length() function takes a single Object which can either be a collection or a String and returns an integer like this:

fn:length() 函数接收一个Object,它可以是一个集合,也可以是一个String,然后像这样返回一个整数。

<p>Length: ${fn:length(string1)}</p>

7.8. The fn:replace() Function

7.8.fn:replace() 函数

The fn:replace() function replaces all occurrences of a substring in a String with another String.

fn:replace()函数用另一个String.替换一个字符串中所有出现的子串。

It takes three arguments; the source String, the substring to lookup in the source and the String to replace all occurrences of the substring just like this:

它需要三个参数;源字符串,要在源中查找的子串和字符串要替换所有出现的子串,就像这样。

<c:set var = "string3" value = "${fn:replace(string1, 'first', 'third')}" />

7.9. The fn:split() Function

7.9.fn:split() 功能

The fn:split() function performs split operation on a String using the specified delimiter. Here is an example usage:

fn:split()函数使用指定的分隔符对String进行分割操作。下面是一个用法示例。

<c:set var = "string3" value = "${fn:split(string1, ' ')}" />

7.10. The fn:startsWith() Function

7.10.fn:startsWith() 函数

The fn:startsWith() function checks the prefix of a String and returns true if it matches a given substring like this:

fn:startsWith()函数检查一个String的前缀,如果它与给定的子串相匹配,则返回true。

<c:if test = "${fn:startsWith(string1, 'This')}">
    <p>String starts with 'This'</p>
</c:if>

7.11. The fn:substring() Function

7.11.fn:substring() 功能

The fn:substring() function creates a substring from a source String at the starting and ending indices specified. We’d use it like this:

fn:substring()函数从一个源字符串中按指定的起始和结束索引创建一个子串。我们会像这样使用它。

<c:set var = "string3" value = "${fn:substring(string1, 5, 15)}" />

7.12. The fn:substringAfter() Function

7.12.fn:substringAfter() 函数

The fn:substringAfter() function checks a source String for a given substring and returns the String immediately after the first occurrence of the specified substring.

fn:substringAfter()函数检查一个源字符串的指定子串,并返回紧随指定子串第一次出现之后的字符串

We’d use it like this:

我们会像这样使用它。

<c:set var = "string3" value = "${fn:substringAfter(string1, 'is')}" />

7.13. The fn:substringBefore() Function

7.13.fn:substringBefore() 函数

The fn:substringBefore() function checks a source String for a given substring and returns the String just before the first occurrence of the specified substring.

fn:substringBefore()函数检查源字符串是否有指定的子串,并返回刚好在指定子串的第一次出现之前的字符串

In our JSP page, it’ll look like this:

在我们的JSP页面中,它将看起来像这样。

<c:set var = "string3" value = "${fn:substringBefore(string1, 'is')}" />

7.14. The fn:toLowerCase() Function

7.14.fn:toLowerCase() 函数

The fn:to LowerCase() function transforms all characters in a String to lowercase and can be used like this:

fn:to LowerCase()函数将字符串中的所有字符转换为小写,可以像这样使用。

<c:set var = "string3" value = "${fn:toLowerCase(string1)}" />

7.15. The fn:toUpperCase() Function

7.15.fn:toUpperCase() 函数

The fn:toUpperCase() function transforms all characters in a String to uppercase:

fn:toUpperCase()函数将字符串中的所有字符转换为大写。

<c:set var = "string3" value = "${fn:toUpperCase(string1)}" />

7.16. The fn:trim() Function

7.16.fn:trim() 函数

The fn:trim() function removes preceding and trailing whitespaces in a String:

fn:trim()函数删除了String:中的前面和后面的空白处。

<c:set var = "string1" value = "This is first String    "/>

9. Conclusion

9.结论

In this extensive article, we’ve looked at the various JSTL tags and how to use them.

在这篇广泛的文章中,我们已经看了各种JSTL标签以及如何使用它们。

As usual, code snippets can be found over on GitHub.

像往常一样,代码片段可以在GitHub上找到over