JavaWeb之JSTL标签

JSP中有了EL可以很方便的引用对象和属性,但是也有一些不足的地方,比如不能遍历对象列表这些,再加上JSTL(Java Standard Tag Library)的话那就完美了。JSTL主要包括core核心库、fmt标签库、fn方法库、SQL标签库、XML标签库。这些库理论知识不多,主要是使用。

一、core核心库

从JavaEE5之后JavaEE5内置了对JSTL的支持,如果是之前的版本需要自己下载引入。http://archive.apache.org/dist/jakarta/taglibs/standard/binaries/jakarta-taglibs-standard-1.1.2.zip下载解析,将这两个jstl.jarstandard.jar引入到WEB-INF/lib下。在jsp中加入<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>然后就可以在jsp中正常使用了。

1.<c:out/>用来输出,除了value还有两个属性,default和escapeXML,如果value属性不存在,会输出default的的值.

<c:out value="out-123"></c:out>

2.<c:if/>用于判断,由于没有if...esle..这样的判断,需要使用<c:choose/><c:when/><c:otherwise/>

<c:choose>
  <c:when test="${1==1 }">
      <c:out value="c:when"></c:out>
  </c:when>
  <c:otherwise>
      <c:out value="c:otherwise"></c:out>
  </c:otherwise>
</c:choose>

3.<c:forEach/>用于循环,类似for 、while

<c:forEach var="num" step="2" begin="2" end ="100">
 <c:out value="${num }"></c:out>
</c:forEach>
View Code

.<c:forEach/>对象列表与map

<%
   List<User> users=new ArrayList<User>();
   users.add(new User("小明",22,true));
   users.add(new User("小李",23,false));
   request.setAttribute("users", users);
   
   Map map=new HashMap();
   map.put("A", 1);
   map.put("B", 2);
   request.setAttribute("map", map);
   
%>
<c:forEach items="${users }" var="user">
<c:out value="Name=${user.name } age=${user.age }"></c:out>
</c:forEach>
<c:forEach items="${map }" var="item" varStatus="varStatu">
<c:out value="IsFirst=${varStatu.first  }  IsLast=${varStatu.last } Index=${varStatu.index } Key=${item.key } age=${item.value }"></c:out><br>
</c:forEach>
View Code

4.<c:forTokens/>与.<c:forEach/>类似,只是数据源只能是字符串

<c:forTokens items="A;B;C;D;E;F;G;H;I;J;K" delims=";" var="item" begin="1" end="6" step="2">
   <c:out value="${item }"></c:out>
</c:forTokens>
View Code

5.<c:set/>

前面的标签只是实现了读,而<c:set/>能实现写的功能。set可以声明一个不存在的对象,也可以修改一个已经存在的对象,或者修改对象的某个属性,只要这个属性可写。set有5个属性:var、value、target、scope、property。支持标签体,可以把值写在value中,也可写在<></>中间。

var:要设置的对象的名,不存在则生成,存在则修改,只能操作int、double、String等基本的数据类型,不能操作JavaBean、Map或复杂的数据类型。

value:要设置的值,可以为EL表达式

scope:和POJO的处的一样

target:类似var,不过只能操作JavaBean、Map这些,与var互补。不过它只能修改已存在的JavaBean、Map,否则会报错。

下面的是修改属性值

 request.setAttribute("use", new User("小明",22,true));
<c:set target="${use}" property="name" value="小小"></c:set>
<c:out value="修改后姓名为:${use.name }"></c:out>
View Code

下面是实现了计数器的功能

<c:set var="totalCount" scope="application">${totalCount+1 }</c:set>
<c:set var="count" scope="session">${count+1 }</c:set>
本站访问的总次数:${totalCount } 个人访问的次数:${count }
View Code

6.<c:remove/>标签 与set标签相反,它是移除只有两个属性var、scope,var只接受字符串不接受EL

<c:remove var="map" scope="page"/>
<c:out value="${map==null?'map已被移除':'map未移除'}"></c:out>
View Code

7.<c:catch/>标签来捕获异常

<c:catch var="e">
   <c:set target="${users}" property="age" value="123"></c:set>
</c:catch >
<c:if test="${e!=null }">
<c:out value="${e.message }"></c:out>
</c:if>
View Code

8.<c:import/>类似include的行为和指令,也可以导入网页,不过import可以导入外网的。

<c:import url="/part.jsp"></c:import>
<c:import url="http://www.cnblogs.com"></c:import>
View Code

9.<c:redirect/> 实现重定向功能,context默认当前的context path,url为相对于context的相对地址。两个都必须是"/"开头。

<c:redirect url="http://www.cnblogs.com"></c:redirect>
<c:redirect url="/part.jsp"></c:redirect>
View Code

10.<c:param/>页面跳转传参使用

<c:redirect url="http://zzk.cnblogs.com/s">
    <c:param name="t" value="b"></c:param>
    <c:param name="w" value="jstl"></c:param>
</c:redirect>
View Code

二、fmt标签库

fmt:format的缩写,从英文名也能猜出它是用来干嘛的,主要是用来格式化的,时间日期数字字符串语言的格式化。在使用它之前需要在jsp中引入,和core库一样,

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

1.<f:requestEncoding/>用于设定request编码只有一个value属性。

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

2.<fmt:setLocale/> Locale本地化的意思。就和语言一样,世界上有几十种语言,为了互相交流,于是就出现了翻译。本地就是做翻译的功能.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<fmt:requestEncoding value="UTF-8"/>
<%
 request.setAttribute("LocaleList", Locale.getAvailableLocales());
%>
<table>
    <tr>
        <th>地区名</th>
        <th>语言</th>
        <th>时间</th>
        <th>数字</th>
        <th>货币</th>
    </tr>
    <jsp:useBean id="date" class="java.util.Date"></jsp:useBean>
    <c:forEach items="${LocaleList}" var="item">
      <fmt:setLocale value="${item }"/>
      <tr>
        <td>${item.displayName }</td>
        <td>${item.displayLanguage }</td>
        <td><fmt:formatDate value="${date }" type="both"/></td>
        <td><fmt:formatNumber value="1000.5"></fmt:formatNumber></td>
        <td><fmt:formatNumber value="1000.5" type="currency"></fmt:formatNumber></td>
      </tr>
    </c:forEach>
</table>
</body>
</html>
View Code

上面的代码通过Locale类获取所有的地区,然后遍历地区,显示出地区名、语言、时间、数字、货币。

其实<fmt:setLocale>还有两个属性,scope和variant.由于scope设置作用域的,默认page,每次设置之后显示的都会是对应的数字货币时间。variant是客户端或操作系统的代号。输出数据尽量使用jstl标签,jstl会自动根据不同的locale来显示不同的内容,EL则不会。在平时开发中服务器会自动设置locale,开发时只需通过request获取即可。

3.<fmt:timeZone></fmt:timeZone> <fmt:setTimeZone/>

Locale只是影响的是时间格式,时区对时间也有影响,<fmt:timeZone></fmt:timeZone>只对标签体内的代码有效。而<fmt:setTimeZone/>和<fmt:setLocale/>一样是设置一定作用域内有效

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
   Map<String,TimeZone> hashMap=new HashMap<String,TimeZone>();
   for(String ID :TimeZone.getAvailableIDs())
   {
       hashMap.put(ID, TimeZone.getTimeZone(ID));
   }
   request.setAttribute("hashMap", hashMap);
%>
<jsp:useBean id="date" class="java.util.Date"></jsp:useBean>
<fmt:timeZone value="Asia/Shanghai">
   现在时刻:<%=TimeZone.getDefault().getDisplayName() %> <fmt:formatDate value="${date }" type="both"/>
</fmt:timeZone>
<table>
    <tr>
        <th>时区ID</th>
        <th>时区</th>
        <th>现在时间</th>
        <th>时差</th>    
    </tr>
    <c:forEach items="${hashMap}" var="item">
      <fmt:setTimeZone value="${item.value }" scope="page"/>
      <tr>
        <td>${item.key }</td>
        <td>${item.value.displayName }</td>
        <td><fmt:formatDate value="${date }" type="both"/></td>
       
        <td>${item.value.rawOffset/60/60/1000}</td>
      </tr>
    </c:forEach>
</table>
</body>
</html>
View Code

上面的代码先使用<fmt:timeZone></fmt:timeZone>显示本地的时间,然后通过TimeZone类获取的全球时区遍历通过<fmt:setTimeZone/>显示不同时区的时间.

 

 4. <fmt:formatNumber/>主要用来格式化数字

属性描述是否必要默认值
value 要显示的数字
type NUMBER,CURRENCY,或 PERCENT类型 Number
pattern 指定一个自定义的格式化模式用与输出
currencyCode 货币码(当type="currency"时) 取决于默认区域
currencySymbol 货币符号 (当 type="currency"时) 取决于默认区域
groupingUsed 是否对数字分组 (TRUE 或 FALSE) true
maxIntegerDigits 整型数最大的位数
minIntegerDigits 整型数最小的位数
maxFractionDigits 小数点后最大的位数
minFractionDigits 小数点后最小的位数
var 存储格式化数字的变量 Print to page
scope var属性的作用域 page

如果type属性为percent或number,那么您就可以使用其它几个格式化数字属性。maxIntegerDigits属性和minIntegerDigits属性允许您指定整数的长度。若实际数字超过了maxIntegerDigits所指定的最大值,则数字将会被截断。

有一些属性允许您指定小数点后的位数。minFractionalDigits属性和maxFractionalDigits属性允许您指定小数点后的位数。若实际的数字超出了所指定的范围,则这个数字会被截断。

数字分组可以用来在每三个数字中插入一个逗号。groupingIsUsed属性用来指定是否使用数字分组。当与minIntegerDigits属性一同使用时,就必须要很小心地来获取预期的结果了。

您或许会使用pattern属性。这个属性可以让您在对数字编码时包含指定的字符。接下来的表格中列出了这些字符。

符号描述
0 代表一位数字
E 使用指数格式
# 代表一位数字,若没有则显示0
. 小数点
, 数字分组分隔符
; 分隔格式
- 使用默认负数前缀
% 百分数
? 千分数
¤ 货币符号,使用实际的货币符号代替
X 指定可以作为前缀或后缀的字符
' 在前缀或后缀中引用特殊字符

5.<fmt:parseNumber>主要用来将字符串转为数字

属性描述是否必要默认值
value 要解析的数字 Body
type NUMBER,,CURRENCY,或 PERCENT number
parseLocale 解析数字时所用的区域 默认区域
integerOnly 是否只解析整型数(true)或浮点数(false) false
pattern 自定义解析模式
timeZone 要显示的日期的时区 默认时区
var 存储待解析数字的变量 Print to page
scope var属性的作用域 page

6.<fmt:formatDate/>主要用来格式化时间

属性描述是否必要默认值
value 要显示的日期
type DATE, TIME, 或 BOTH date
dateStyle FULL, LONG, MEDIUM, SHORT, 或 DEFAULT default
timeStyle FULL, LONG, MEDIUM, SHORT, 或 DEFAULT default
pattern 自定义格式模式
timeZone 显示日期的时区 默认时区
var 存储格式化日期的变量名 显示在页面
scope 存储格式化日志变量的范围 页面

7.<fmt:parseDate/>主要用来将字符串转为时间格式

属性描述是否必要默认值
value 要显示的日期
type DATE, TIME, 或 BOTH date
dateStyle FULL, LONG, MEDIUM, SHORT, 或 DEFAULT default
timeStyle FULL, LONG, MEDIUM, SHORT, 或 DEFAULT default
pattern 自定义格式模式
timeZone 显示日期的时区 默认时区
var 存储格式化日期的变量名 显示在页面
scope 存储格式化日志变量的范围 页面

三、fn方法库

fn:function,提供了一些常用的方法,这些和C#中的基本一样所以没啥说的,比较简单。使用前引入方法库

1.fn:contains判断字符串是否包含,区分大小写

2.fn:containsIgnoreCase判断,不区分大小写

3.fn:endsWith判断字符串以什么结尾

4.fn:startsWith判断字符串以什么开头

5.fn:indexOf 查找字符串在什么位置

6.fn:split 字符串以什么分隔开

7.fn:join将字符串数组以字符合并

7.fn:escapeXml

8.fn:length判断字符串长度

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
fn:contains:<br>
${fn:contains("abc","a") }<br>
${fn:contains("abc","A") }<br>
fn:containsIgnoreCase:<br>
${fn:containsIgnoreCase("abc","A") }<br>
fn:endsWith:<br>
${fn:endsWith("a;png;",';')}
${fn:endsWith("a;png;",'png;')}<br>
fn:startsWith:<br>
${fn:startsWith("_png","_")}
${fn:startsWith("_png_abc",'_')}<br>
fn:indexOf
${fn:indexOf("a;b;c;",';') }<br>
fn:split:<br>
<c:set var="splits" value="${fn:split('a;b',';')}"></c:set>
<c:forEach items="${splits}" var="item">
    <c:out value="${item }"></c:out><br>
</c:forEach><br>
fn:length:
${fn:length("abdcd123")}<br>
<c:set var="string1" value="${fn:split('a;b;c', ';')}" />
<c:set var="string2" value="${fn:join(string1, ';')}" />
<p>字符串为 : ${string2}</p>
fn:escapeXml:<br>
<c:import url="http://www.cnblogs.com" var="source"></c:import>
${fn:escapeXml(source) }
</body>
</html>
View Code

 四、SQL、XML标签库

这两个标签库会分别在JDBC、XML中学习,还有一些国际化的标签会放在国际化多语言中学习。

posted @ 2017-03-19 18:29  社会主义接班人  阅读(1332)  评论(0编辑  收藏  举报