Skip to content

11 jstl标签库

官网

  • JSTL(JavaServer Pages Standard Tag Library,JSP标准标签库)是由Apache的Jakarta项目组开发的一个标准的通用型标签库,已纳入JSP 2.0规范,是JSP 2.0最重要的特性之一。

  • JSTL主要提供给Java Web开发人员一个标准通用的标签函数库,标签库同时支持EL用于获取数据,Web开发人员能够利用此标签库取代传统直接在页面中嵌入Java程序的做法,以提高程序的可读性和易维护性。

  • JSTL由5个不同功能的标签库组成,在JSTL规范中为这5个标签库分别指定了不同的URI,并对标签库的前缀作出了约定。

标签库前缀名称URI示例
核心标签库chttp://java.sun.com/jsp/jstl/core<c:out>
I18N标签库fmthttp://java.sun.com/jsp/jstl/fmtfmt:formatDate
SQL标签库sqlhttp://java.sun.com/jsp/jstl/sqlsql:query
XML标签库xhttp://java.sun.com/jsp/jstl/xml<x:forBach>
函数标签库fnhttp://java.sun.com/jsp/jstl/functionsfn:split
  • 核心标签库
    • 包含实现Web应用的通用操作的标签。
      • 例如,输出变量内容的<c:out>标签、用于条件判断的<c:if>标签,用于循环遍历的<c:forEach>标签等。
  • I18N标签库
    • 包含实现Web应用程序的国际化的标签。
    • 例如,设置JSP页面的本地信息、设置JSP页面的时区、使本地敏感的数据(如数值、日期)按照JSP页面中设置的本地格式进行显示等。
  • SQL标签库
    • 包含用于访问数据库和对数据库中的数据进行操作的标签。
      • 例如,从数据源中获得数据库连接、从数据库表中检索数据等。由于在实际开发中,多数应用采用分层开发模式,JSP页面通常仅用作表现层,并不会在JSP页面中直接操作数据库,所以此标签库在分层的较大项目中较少使用,在小型不分层的项目中可以通过SQL标签库实现快速开发。
  • XML标签库
    • 包含对XML文档中的数据进行操作的标签。
      • 例如,解析XML文档、输出XML文档中的内容,以及迭代处理XML文档中的元素等。
  • 函数标签库
    • 由JSTL提供一套EL自定义函数,包含了JSP页面制作者经常要用到的字符串操作, 例如,提取字符串中的子字符串、获取字符串的长度和处理字符串中的空格等。

11.1 JSTL的安装使用

目前JSTL最新版本为1.2,需在Servlet 2.5、JSP 2.1的环境中运行。JSTL与所需环境的版本对应关系

VersionJSTL versionRequirementsGetting the Taglib
Standard 1.2.3JSTL 1.2Servlet 2.5, JavaServer Pages 2.1download (javadoc)
Standard 1.1JSTL 1.1Servlet 2.4, JavaServer Pages 2.0download
Standard 1.0JSTL 1.0Servlet 2.3, JavaServer Pages 1.2download

如果要使用JSTL,首先需要下载JSTL标签库的jar包

添加maven依赖

<dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

11.2 核心标签库

标签描述
<c:out>用于在JSP中显示数据,就像<%= ... >
<c:set>用于保存数据
<c:remove>用于删除数据
<c:catch>用来处理产生错误的异常状况,并且将错误信息储存起来
<c:if>与我们在一般程序中用的if一样
<c:choose>本身只当做<c:when><c:otherwise>的父标签
<c:when><c:choose>的子标签,用来判断条件是否成立
<c:otherwise><c:choose>的子标签,接在<c:when>标签后,当<c:when>标签判断为false时被执行
<c:import>检索一个绝对或相对 URL,然后将其内容暴露给页面
<c:forEach>基础迭代标签,接受多种集合类型
<c:forTokens>根据指定的分隔符来分隔内容并迭代输出
<c:param>用来给包含或重定向的页面传递参数
<c:redirect>重定向至一个新的URL.
<c:url>使用可选的查询参数来创造一个URL

在jsp中引入taglib

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

代码示例

html
<%@ page import="com.neuedu.entity.User" %><%--
  Created by IntelliJ IDEA.
  User: root
  Date: 2020/12/14
  Time: 11:17
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <title>Title</title>
</head>
<body>


<c:out value="${1+2}"/>
<c:out value="<h1>标题</h1>" escapeXml="false"/>
<hr/>



<h3>set</h3>
<c:set var="salary" scope="session" value="${2000*2}"/>
<c:out value="${salary}"/> <br/>
<hr/>

<h3>remove</h3>
<c:remove var="salary" scope="session"/>
remove_salary : <c:out value="${salary}"/> <br/>
<hr/>


<h3>catch</h3>
<c:catch var="catchException">
    <% int x = 5 / 0;%>
</c:catch>

catchException: ${catchException} <br/>

<hr/>



<h3>If</h3>
<c:set var="salary" scope="session" value="${2000*2}"/>
<c:if test="${salary > 2000}">
    <p>我的工资为: <c:out value="${salary}"/><p>
</c:if>
<hr/>

<h3>多分支 choose when otherwise</h3>
<%--低等<4000  中等>=4000 && <8000  高等 >8000 --%>
<c:set var="sal" value="${2000}"/>
<c:choose>
    <c:when test="${sal<4000}">
        低等
    </c:when>
    <c:when test="${sal>=4000 and sal<8000}">
        中等
    </c:when>
    <c:otherwise>
        高等
    </c:otherwise>
</c:choose>
<hr/>



<h3>import</h3>
<c:import url="content.jsp"/>
<hr/>

</body>
</html>

上述import标签需要有content.jsp支持content.jsp代码如下:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

待import文本

循环标签

html
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="com.neuedu.entity.User" %>
<%@ page import="java.util.Date" %><%--
  Created by IntelliJ IDEA.
  User: root
  Date: 2020/12/14
  Time: 13:32
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <title>Title</title>
</head>
<body>

<%
    //在Servlet查询了一个User的集合

    List<User> userList = new ArrayList();

    userList.add(new User(101,"root","123456",new Date()));
    userList.add(new User(102,"admin","223456",new Date()));
    userList.add(new User(103,"dsfasdf","323456",new Date()));
    userList.add(new User(104,"jshand","423456",new Date()));
    userList.add(new User(105,"xuusu","523456",new Date()));
    userList.add(new User(106,"sssg","623456",new Date()));
    userList.add(new User(107,"sadff","723456",new Date()));

    request.setAttribute("userList",userList);


%>

<table cellpadding="0" cellspacing="0" border="1" width="100%" >
    <tr>
        <td>序号</td>
        <td>id</td>
        <td>用户名</td>
        <td>密码</td>
        <td>日期</td>
    </tr>

    <c:forEach items="${userList}"  varStatus="stat" var="user" begin="0" end="6" step="2">
        <tr>
<%--            <td><c:out value="${stat.index}"/> </td>--%>
            <td><c:out value="${stat.count}"/> </td>
            <td><c:out value="${user.userId}"/> </td>
            <td><c:out value="${user.userName}"/> </td>
            <td><c:out value="${user.password}"/> </td>
            <td><c:out value="${user.birthday}"/> </td>
        </tr>
    </c:forEach>
</table>




<hr/>




<%
    String names = "张飞,李逵,孙悟空";
    request.setAttribute("names",names);
%>


<c:forTokens items="${names}" delims="," var="name" >
    <p><c:out value="${name}"/> </p>
</c:forTokens>


</body>
</html>

<c:redirect/> 和<c:url/>标签

html
<%--重定向 --%>
<%--<c:redirect url="/index.jsp" context="/manager"/>--%>

<!--构造URL -->
<c:url value="http://127.0.0.1:8080/web/index.jsp" var="myurl">
    <c:param name="name" value="jshand"/>
    <c:param name="age" value="age"/>
</c:url>

<a href="${myurl}">第一个超链接</a>
<a href="${myurl}">第2个超链接</a>
<a href="${myurl}">第3个超链接</a>
<a href="${myurl}">第4个超链接</a>
<a href="${myurl}">第5个超链接</a>

11.3 格式化标签

JSTL格式化标签用来格式化并输出文本、日期、时间、数字。引用格式化标签库的语法如下:

标签描述
<fmt:formatNumber>使用指定的格式或精度格式化数字
<fmt:parseNumber>解析一个代表着数字,货币或百分比的字符串
<fmt:formatDate>使用指定的风格或模式格式化日期和时间
<fmt:parseDate>解析一个代表着日期或时间的字符串
<fmt:bundle>绑定资源
<fmt:setLocale>指定地区
<fmt:setBundle>绑定资源
<fmt:timeZone>指定时区
<fmt:setTimeZone>指定时区
<fmt:message>显示资源配置文件信息
<fmt:requestEncoding>设置request的字符编码

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

11.3.1 日期字符串格式化

html
<%--
  Created by IntelliJ IDEA.
  User: root
  Date: 2020/12/14
  Time: 14:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h3>数字格式化:</h3>
<c:set var="balance" value="120000.2309" />




6584m658,465,465,165

<p>格式化数字 (1): <fmt:formatNumber value="${balance}"      type="currency"/></p>



<p>格式化数字 (2): <fmt:formatNumber type="number"   maxIntegerDigits="3" value="${balance}" /></p>
<p>格式化数字 (3): <fmt:formatNumber type="number"  maxFractionDigits="3" value="${balance}" /></p>
<p>格式化数字 (4): <fmt:formatNumber type="number"  groupingUsed="false" value="${balance}" /></p>

<p>格式化数字 (5): <fmt:formatNumber type="percent"  maxIntegerDigits="3" value="${balance}" /></p>
<p>格式化数字 (6): <fmt:formatNumber type="percent"  minFractionDigits="10" value="${balance}" /></p>
<p>格式化数字 (7): <fmt:formatNumber type="percent"  maxIntegerDigits="3" value="${balance}" /></p>


<p>格式化数字 (8): <fmt:formatNumber type="number"   pattern="###.###E0" value="${balance}" /></p>
<p>美元 :


    <fmt:setLocale value="en_US"/>


    <fmt:formatNumber value="${balance}" type="currency"/></p>

<hr/>

<fmt:parseNumber var="i" type="number" value="${balance}" />
<p>数字解析 (1) : <c:out value="${i}" /></p>
<fmt:parseNumber var="i" integerOnly="true"
                 type="number" value="${balance}" />
<p>数字解析 (2) : <c:out value="${i}" /></p>



<hr/>

<h3>日期格式化:</h3>
<c:set var="now" value="<%=new java.util.Date()%>" />

<p>日期格式化 (1): <fmt:formatDate type="time"     value="${now}" /></p>
<p>日期格式化 (2): <fmt:formatDate type="date"   value="${now}" /></p>
<p>日期格式化 (3): <fmt:formatDate type="both"  value="${now}" /></p>
<p>日期格式化 (4): <fmt:formatDate type="both"  dateStyle="short" timeStyle="short"   value="${now}" /></p>
<p>日期格式化 (5): <fmt:formatDate type="both"   dateStyle="medium" timeStyle="medium"   value="${now}" /></p>
<p>日期格式化 (6): <fmt:formatDate type="both" dateStyle="long" timeStyle="long"   value="${now}" /></p>

<p>日期格式化 (7): <fmt:formatDate pattern="yyyy-MM-dd"  value="${now}" /></p>



<hr/>
<h3>日期解析:</h3>
<c:set var="now" value="20-10-2015" />

<fmt:parseDate value="${now}" var="parsedEmpDate"  pattern="dd-MM-yyyy" />
<p>解析后的日期为: <c:out value="${parsedEmpDate}" /></p>

</body>
</html>

11.3.2 时区相关的

html
<%--
  Created by IntelliJ IDEA.
  User: root
  Date: 2020/12/14
  Time: 14:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>


<body>


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


<c:set var="now" value="<%=new java.util.Date()%>" />
<table border="1" width="100%">
    <tr>
        <td width="100%" colspan="2" bgcolor="#0000FF">
            <p align="center">
                <b>
                    <font color="#FFFFFF" size="4">Formatting:
                        <fmt:formatDate value="${now}" type="both"   timeStyle="long" dateStyle="long" />
                    </font>
                </b>
            </p>
        </td>
    </tr>

    <c:forEach var="zone"
               items="<%=java.util.TimeZone.getAvailableIDs()%>">
        <tr>
            <td width="51%">
                <c:out value="${zone}" />
            </td>
            <td width="49%">


                <fmt:timeZone value="${zone}">
                    <fmt:formatDate value="${now}"   type="both" />
                </fmt:timeZone>
            </td>
        </tr>
    </c:forEach>
</table>
</body>


</html>

11.3.3 国际化

Java中的国际化

新建 neuedu_hrbu_java1_en_US.properties 内容如下:、

properties
column1=Product
column2=Services
column3=About
hello=hello my name {0},age{1}

新建 neuedu_hrbu_java1_zh_CN.properties 内容如下

properties
column1=产品
column2=服务
column3=关于
hello=你好,我叫{0},我今年 {1}

idea中需要设置属性文件转码

在Java中使用国际化资源(单元测试)

java
package com.neuedu.resources;

import org.junit.Test;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * 项目:      el_jstl
 * 类名:       BundleResources
 * 创建时间:  2020/12/14  15:30
 * 描述 :
 * 作者 :     张金山
 * QQ :     314649444
 * Site:      https://jshand.gitee.io
 *
 * 资源束
 */
public class BundleResources {

    @Test
    public void test(){

        //根据语言环境查找
        ResourceBundle bundle = ResourceBundle.getBundle("neuedu_hrbu_java1");
        String column3 = bundle.getString("column3");
        System.out.println(column3);


        //指定语言环境
        Locale locale = new Locale("en","US");
        ResourceBundle bundle2 = ResourceBundle.getBundle("neuedu_hrbu_java1",locale);
        String column32 = bundle2.getString("column3");
        System.out.println(column32);




//        String str = bundle.getString("hello");
        String str = bundle2.getString("hello");
        String formatStrr = MessageFormat.format(str,"jshand",18);

        System.out.println("formatStrr: "+formatStrr);

    }

}

jstl中使用国

html
<%--
  Created by IntelliJ IDEA.
  User: root
  Date: 2020/12/14
  Time: 16:06
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

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


<html>
<head>
    <title>Title</title>
    <script>
        function changelag() {

            document.forms[0].submit();
        }


    </script>
</head>
<body>

<%

    String lang = request.getParameter("lang");

    if (lang == null || "".equals(lang)) {
        lang = "zh_CN";
    }
    request.setAttribute("lang", lang);
%>


<form method="post" action="">

    <select onchange="changelag()" name="lang">
        <option value="zh_CN" <c:if test="${lang=='zh_CN'}">selected</c:if>>中文</option>
        <option value="en_US" <c:if test="${lang=='en_US'}">selected</c:if>>英文</option>

    </select>

    <fmt:setLocale value="${lang}"/>

    <h3>setBundle</h3>
    <fmt:setBundle basename="neuedu_hrbu_java1" var="bundle"/>


    <table cellspacing="0" cellpadding="0" border="1" width="80%">
        <tr>
            <td><fmt:message key="form.c1" bundle="${bundle}"/></td>
            <td><input name="username"></td>
        </tr>
        <tr>
            <td><fmt:message key="form.c2" bundle="${bundle}"/></td>
            <td><input name="password"></td>
        </tr>

    </table>

    <h3>bundle</h3>

    <fmt:bundle basename="neuedu_hrbu_java1" prefix="form.">
        <table cellspacing="0" cellpadding="0" border="1" width="80%">
            <tr>
                <td><fmt:message key="c1"/></td>
                <td><input name="username"></td>
            </tr>
            <tr>
                <td><fmt:message key="c2"/></td>
                <td><input name="password"></td>
            </tr>

        </table>
    </fmt:bundle>
</form>


</body>
</html>

11.4 函数库标签

在jsp中引入fn类库

JSTL包含一系列标准函数,大部分是通用的字符串处理函数。引用JSTL函数库的语法如下:

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

函数描述
fn:contains()测试输入的字符串是否包含指定的子串
fn:containsIgnoreCase()测试输入的字符串是否包含指定的子串,大小写不敏感
fn:endsWith()测试输入的字符串是否以指定的后缀结尾
fn:escapeXml()跳过可以作为XML标记的字符
fn:indexOf()返回指定字符串在输入字符串中出现的位置
fn:join()将数组中的元素合成一个字符串然后输出
fn:length()返回字符串长度
fn:replace()将输入字符串中指定的位置替换为指定的字符串然后返回
fn:split()将字符串用指定的分隔符分隔然后组成一个子字符串数组并返回
fn:startsWith()测试输入字符串是否以指定的前缀开始
fn:substring()返回字符串的子集
fn:substringAfter()返回字符串在指定子串之后的子集
fn:substringBefore()返回字符串在指定子串之前的子集
fn:toLowerCase()将字符串中的字符转为小写
fn:toUpperCase()将字符串中的字符转为大写
fn:trim()移除首尾的空白符

11.5 SQL标签

JSTL SQL标签库提供了与关系型数据库(Oracle,MySQL,SQL Server等等)进行交互的标签。引用SQL标签库的语法如下:

<%@ taglib prefix="sql" 
           uri="http://java.sun.com/jsp/jstl/sql" %>
标签描述
<sql:setDataSource>指定数据源
<sql:query>运行SQL查询语句
<sql:update>运行SQL更新语句
<sql:param>将SQL语句中的参数设为指定值
<sql:dateParam>将SQL语句中的日期参数设为指定的java.util.Date 对象值
<sql:transaction>在共享数据库连接中提供嵌套的数据库行为元素,将所有语句以一个事务的形式来运行

11.6 XML 标签

JSTL XML标签库提供了创建和操作XML文档的标签。引用XML标签库的语法如下:

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

在使用xml标签前,你必须将XML 和 XPath 的相关包拷贝至你的<Tomcat 安装目录>\lib下:

标签描述
<x:out>与<%= ... >,类似,不过只用于XPath表达式
<x:parse>解析 XML 数据
<x:set>设置XPath表达式
<x:if>判断XPath表达式,若为真,则执行本体中的内容,否则跳过本体
<x:forEach>迭代XML文档中的节点
<x:choose><x:when><x:otherwise>的父标签
<x:when><x:choose>的子标签,用来进行条件判断
<x:otherwise><x:choose>的子标签,当<x:when>判断为false时被执行
<x:transform>将XSL转换应用在XML文档中
<x:param><x:transform>共同使用,用于设置XSL样式表

Released under the MIT License.