JSTL是sun公司开发的一套标签库,主要为基本输入输出、流程控制、迭代操作和URL操作提供了定制标签,从而替换页面中的脚本代码。
1、核心标签库
JSTL核心标签库总共有13个,分为4类,如下表
类别 | 标签 |
表达式控制 | out、set、remove、catch |
流程控制 | if、choose、when、otherwise |
循环控制 | forEach、forTokens |
URL操作 | import、url、redirect |
在页面中使用JSTL核心标签需完成以下2步:
<1>导入jstl.jar和standerd.jar两个JSTL的jar文件;
<2>在jsp页面中使用<%@tablib url=”http://java.sun.com/jsp/jstl/core” prefix=”c” %>元素导入标签库。
1.1、表达式控制
1) <c:set>
<c:set>用于在jsp中保存数据将指定的数据保存在指定范围的变量中,格式为:
<c:setvalue=”value” var=”varName” [scope=”{page|request|session|
application}”]>
此外,<c:set>还可以将指定的数据保存到指定对象(javabean、map)的属性中,格式
<c:setvalue=”value” target=”target” property=”propertyName”>
参数值 | 描述 |
value | 指定要保存的对象,可以采用el表达式 |
var | 指定保存后对象的名字 |
scope | 指定保存在那个范围中 |
target | 指定将要保存的对象保存到那个目标对象中 |
property | 指定target的属性名 |
用法举例:
<c:set value="ssl" var="name"scope="page"/>
<c:set value="ssl"target="${requestScope.map}" property="name"/>
<c:out value="${pageScope.name}"/>
<c:out value="${requestScope.map.name}"/>
2) <c:out>
<c:out>用于在jsp页面中显示数据,格式
<c:out value=”value” [default=”defaultValue”]>
default:当value为null时,显示defaultValue
3) <c:remove>
<c:remove>用于在jsp页面中删除变量,格式
<c:remove var=”varName” [scope=”page|request|session|application”]>
4) <c:catch>
用于在jsp页面中捕获异常,并将异常信息保存在指定的变量中。格式为:
<c:catch [var=”varName”]>
需要捕获异常的代码段
</c:catch>
其中,var用来指定保存异常信息的变量名。
<c:catch var="err">
<%
String str=null;
str.trim();
%>
</c:catch>
错误信息:<c:out value="${err}" default="未发生错误"/>
1.2、流程控制
5) <c:if>
<c:if>与if的作用一致,进行条件判断,语法格式为:
<c:if test=”${condition}” [var=”varName”] [scope=”{page|request|session|
application}”]>
满足条件时,将执行的代码段
</c:if>
其中test:为条件表达式,采用EL表达式,var存放条件表达式结果的变量。
<c:if test="${param.name=='ssl'}"var="result">
ssl,你好
</c:if>
条件判断的结果:<c:out value="${result}"/>
6) <c:choose>
<c:choose>、<c:when>、<c:otherwise>配套使用进行条件分支的流程控制,与switch的功能一致。其中<c:when>和<c:otherwie>必须放在<c:choose>标签内,<c:when>必须位于<c:otherwise>之前。每个<c:when>代表一个分支,当所有分支都不满足时,将执行<c:otherwise>代码段,如下
<c:choose>
<c:when test=”${condition}”>
为真时的代码段
</c:when>
<c:when test=”${condition}”>
为真时的代码段
</c:when>
<c:otherwise>
所有条件都不满足时的代码段
</c:otherwise>
</c:choose>
<%
Random random=new Random();
request.setAttribute("luck", random.nextInt(10));
%>
<c:choose>
<c:when test="${luck==6}">恭喜,幸运数字6</c:when>
<c:when test="${luck==8}">恭喜,幸运数字8</c:when>
<c:when test="${luck==9}">恭喜,幸运数字9</c:when>
<c:otherwise>谢谢您的参与,欢迎下次再来</c:otherwise>
</c:choose>
1.3、循环控制
7) <c:forEach>
<c:forEach>用做循环控制,当条件成立时执行<c:forEach>标签内的代码,常常用于迭代集合元素。迭代元素时语法格式为:
<c:forEach items=”collection” begin=”begin” end=”end”[step=”step”]
[var=”varName”] [varStatus=”varStatusName”]>
循环执行的代码
</c:forEach>
循环控制的格式:
<c:forEach begin=”begin” end=”end” [step=”step”]
[var=”varName”] [varStatus=”varStatusName”]>
循环执行的代码
</c:forEach>
参数 | 说明 |
items | 被遍历的集合对象 |
begin | 开始位置,必须大于等于0,默认为0 |
end | 结束位置,默认为最后一个元素 |
step | 每次循环的增量值(步长),默认为1 |
var | 指向当前成员的引用(变量) |
varStatus | 存放当前成员相关信息的变量,主要有index(当前成员的索引值)、count(已访问过的成员数)、first(是否为第一个成员)、last(是否为最后一个成员) |
<!-- 循环操作 -->
<table>
<c:forEach begin="0"end="8" varStatus="status">
<tr><td>id</td><td>${status.index}</td></tr>
</c:forEach>
</table>
<%
String[] names=new String[]{"ssl","lff","cj"};
request.setAttribute("names",names);
%>
<!-- 遍历集合 -->
<c:forEach items="${names}"var="name">
${name}<br>
</c:forEach>
<!-- 遍历Map元素 -->
<%
Map<String,String> map=new HashMap<String,String>();
map.put("name", "ssl");
map.put("address", "shanghai");
map.put("school","dhu");
request.setAttribute("map", map);
%>
<!-- var指定的是entry对象 -->
<c:forEach items="${map}"var="entry">
${entry.key}${entry.value}<br>
</c:forEach>
8) <c:forTokens>
<c:forTokens>用于遍历一个字符串中所有由定义符号所分割的成员,格式为:
<c:forTokens items=”str” delims=”delimiters” begin=”begin”end=”end” [step=”step”] [var==”varName”] [varStatus=”varStatusName”]>
条件满足时被循环执行的代码段
</c:forTokens>
参数 | 说明 |
items | 被分割的字符串 |
delims | 用做分割的字符串 |
begin | 开始位置,必须大于等于0,默认为0 |
end | 结束位置,默认为最后一个元素 |
step | 每次循环的增量值(步长),默认为1 |
var | 指向当前成员的引用(变量) |
varStatus | 存放当前成员相关信息的变量,主要有index(当前成员的索引值)、count(已访问过的成员数)、first(是否为第一个成员)、last(是否为最后一个成员) |
<%
String names="ssl,lff,cj";
request.setAttribute("names",names);
%>
<c:forTokens items="${names}"delims="," var="name">
${name}<br>
</c:forTokens>
1.4、URL操作
9) <c:import>
<c:import>用于将一个静态或动态文件包含到该jsp页面中,所包含的对象不再局限于本web应用程序,其他web应用程序中的文件或FTP资源同样可以被包含进来。
10) <c:url>
<c:url>在jsp页面中产生一个URL。语法格式:
<c:url value=”url” [conetxt=”context”] [var=”varName”] [scope=”{page|
request|session|application}”]>
[<c:param name=”paramName”value=”paramValue”/>]
</c:url>
参数 | 说明 |
value | 指定url值 |
context | 同一个容器的其他应用中的URL资源,以/开头 |
var | 保存生成url内容的变量 |
scope | var变量的作用域 |
c:param | 可以传递URL参数 |
<c:url value="http://www.baidu.com"var="url">
<c:param name="name"value="ssl"/>
</c:url>
<a href="${url}">百度</a>
11) <c:redirect>
<c:redirect>用于请求重定向,格式如下
<c:redirect value=”url” [conetxt=”context”] >
[<c:param name=”paramName”value=”paramValue”/>]
</c:redirect>
2、格式化标签库
JSTL格式化标签库主要提供对数字、日期的格式化操作。在jsp页面中使用<%@tablib url=”http://java.sun.com/jsp/jstl/fmt” prefix=”fmt” %>元素导入标签库。主要的标签有:
1) <fmt:formatNumber>
<fmt:formatNumber>实现数字的格式化,语法如下
<fmt:formatNumber value=”value”
[var=”varName”]
[scope=”{page|request|session|application}”]
[type=”{number|currency|percent}”]
[currencyCode=”currrencyCode”]
[currencySymbol=”currencySymbol”]
[groupingUsed=”{true|false}”]
[maxFractionDigits=”maxFractionDigits”]
[maxIntegerDigits=”maxIntegerDigitals”]
[minFractionDigits=”minFractionDigits”]
[minIntegerDigits=”minIntegerDigitals”]
[pattern=”pattern”]/>
参数 | 说明 |
value | 用于格式化的数字 |
var | 存放格式化结果的变量 |
scope | var变量的作用范围 |
type | 数字、货币、百分比 |
currencyCode | 标准的货币代码,如cny(人民币)、$(美元) |
currencySymbol | 标准的货币符号,如¥、$ |
groupingUsed | 是否将数字进行区隔,如123,456.0 |
maxFractionDigits | 最多小数位 |
maxIntegerDigits | 最多整数位 |
minFractionDigits | 最少小数位 |
minIntegerDigits | 最少整数位 |
pattern | 格式化数字格式 |
<fmt:formatNumber value="6789.3581"
var="result"
type="currency"
maxFractionDigits="2"
groupingUsed="true"/>
${result}<br>
<fmt:formatNumber value="0.653789"
type="percent"
var="result"
maxFractionDigits="2"
groupingUsed="false"/>
${result}<br>
2) <fmt:parseNumber>
<fmt:parseNumber>实现将字符串形式的数字、货币、百分比转换成数字;语法格式为
<fmt:parseNumber value=”value”
[var=”varName”]
[scope=”{page|request|session|application}”]
[type=”{number|currency|percent}”]
[parseLocale=”parseLocale”]
[integerOnly=”{true|false}”]
[pattern=”pattern”]/>
参数 | 说明 |
value | 用于格式化的数字 |
var | 存放格式化结果的变量 |
scope | var变量的作用范围 |
type | 数字、货币、百分比 |
parseLocale | 语言地区代码,如zh_CN(中文)、en(英文) |
integerOnly | 是否只显示整数部分 |
pattern | 格式化数字格式 |
<fmt:parseNumber value="¥6789.3"
var="result"
type="currency"/>
${result}<br>
<fmt:parseNumber value="3.1415926 圆周率"
var="result"/>
${result}<br>
<fmt:parseNumber value="78.90%"
var="result"
type="percent"/>
${result}<br>
3) <fmt:formatDate>
<fmt:formatDate>实现格式化时间和日期,语法格式如下:
<fmt:formatDate value=”value”
[var=”varName”]
[scope=”{page|request|session|application}”]
[type=”{time|date|both}”]
[dateStyle={“default|short|medium|long|full”}]
[timeStyle={“default|short|medium|long|full”}]
[timeZone=”timeZone”]
[pattern=”pattern”]/>
参数 | 说明 |
value | 用于格式化的数字 |
var | 存放格式化结果的变量 |
scope | var变量的作用范围 |
type | 时间、日期、时间和日期 |
dateStyle | 日期的显示方式 |
timeStyle | 时间的显示方式 |
timeZone | 设置时区,如CST(中部标准时间) |
pattern | 格式化时间,日期的格式,如yyyy-MM-dd hh:mm:ss |
<jsp:useBean id="now" class="java.util.Date"/>
<fmt:formatDate value="${now}"
var="result"
type="date"
pattern="yyyy-MM-dd"/>
${result}<br>
<fmt:formatDate value="${now}"
var="result"
type="both"
pattern="yyyy-MM-ddhh:mm:ss"/>
${result}<br>
4) <fmt:parseDate>
<fmt:parseDate>将字符串形式的时间和日期转换为日期时间类型,语法格式如下
<fmt:parseDate value=”value”
[var=”varName”]
[scope=”{page|request|session|application}”]
[type=”{time|date|both}”]
[dateStyle={“default|short|medium|long|full”}]
[timeStyle={“default|short|medium|long|full”}]
[timeZone=”timeZone”]
[pattern=”pattern”]/>
<c:set value="2010-05-01 06:00:44" var="now"/>
<fmt:parseDate value="${now}"
var="result"
type="date"
pattern="yyyy-MM-dd"/>
${result}<br>
<fmt:parseDate value="${now}"
var="result"
type="both"
pattern="yyyy-MM-ddhh:mm:ss"/>
${result}<br>
5) 其他标签
格式化标签库,还有<fmt:setTimeZone>、<fmt:timeZone>、<fmt:setLocale>、<fmt:requestEncoding>、<fmt:setBundle>、<fmt:message>、<fmt:param>、<fmt:bundle>等标签。
3、自定义标签
自定义标签是用户自定义的jsp页面元素,通过封装反复执行的代码使之可以在多个应用程序之间重复使用,从而提高开发效率。
自定义标签的一般步骤:
1) 编写标签处理类,一般继承TagSupport类
方法名 | 描述 |
doStartTag | 遇到自定义标签开始时调用该方法,返回值可以为 SKIP_BODY:表示不处理标签体,直接调用doEndTag EVAL_BODY_INCLUDE:正常执行标签体 |
doAfterBody | 重复执行标签体内容的方法,返回值 SKIP_BODY:表示不处理标签体,直接调用doEndTag EVAL_BODY_AGAIN:重复执行标签体内容 |
doEndTag | 遇到自定义标签结束时调用该方法,返回值可以为 SKIP_PAGE:忽略标签后面JSP的内容,终止JSP页面执行; EVAL_PAGE:处理标签后,继续处理JSP后面的内容 |
release | 释放所获得的所有资源 |
2) 创建标签库描述文件(TLD)
采用XML文件格式来描述用户自定义的标签库,该文件与web应用的配置文件web.xml在同级目录,主要内容如下
<taglib>
<tlib-version>taglib1.0</tlib-version> <!---版本号-->
<jsp-version>jsp2.0</jsp-version> <!---JSP版本号-->
<short-name>customtag</short-name><!---默认前缀-->
<uri>http://xxxx.yyy.zzz/customtag</uri><!---访问标识符-->
<tag> <!---tag元素定义一个标签-->
<name>permission</name> <!---标签名-->
<tag-class>customtags.PermissionTag</tag-class><!---实现类-->
<body-content>jsp</body-content><!--标签体内容,取值为empty(没有标签体)、jsp(标签体可以有jsp程序代码)、tagdependent(标签体的内容由标签自己处理)-->
<attribute> <!—定义属性,对应实现类的属性-->
<name>module</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue> <!—属性值是否支持jsp表达式-->
</attribute>
</tag>
</taglib>
3) 在jsp页面中引入标签库
<%@ tag prefix=”customtag” uri=http://xxx.yyy.zzz/customtag%>
4) 在jsp页面中使用标签
<customtag:permission module=”manager”>
….
</customtag:permission>
示例如下
/**实现类*/
public class PermissionTag extends TagSupport
{
/**
*
*/
private static final long serialVersionUID = 1L;
private String module;
private String privilege;
public StringgetModule()
{
return module;
}
public void setModule(String module)
{
this.module = module;
}
public StringgetPrivilege()
{
return privilege;
}
public void setPrivilege(String privilege)
{
this.privilege = privilege;
}
@Override
public int doStartTag() throws JspException
{
boolean result=true;
HttpServletRequest request=(HttpServletRequest) pageContext.getRequest();
return result?EVAL_BODY_INCLUDE:SKIP_BODY;
}
}
/**标签描述文件*/
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//SunMicrosystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.2</tlibversion>
<jspversion>1.1</jspversion>
<shortname>ssl</shortname>
<uri>http://www.ssl.org/</uri>
<tag>
<name>permission</name>
<tagclass>org.ssl.book.web.tag.PermissionTag</tagclass>
<bodycontent>JSP</bodycontent>
<attribute>
<name>module</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>privilege</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
/**jsp页面*/
<%@ taglib uri="http://www.ssl.org/" prefix="ssl"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>首页</title>
</head>
<body>
<h1>book-web</h1>
<ssl:permission privilege="add"module="department">
<h1>permission</h1>
</ssl:permission>
</body>
</html>