1. 程式人生 > >JSTL標籤庫學習總結

JSTL標籤庫學習總結

最近沒什麼專案,部門經理開會讓我們複習學習EE的知識,每個人分一部分自行研究總結,今天總結了一下JSTL標籤的使用,方便以後工作中用到時複習使用。

一、為什麼要使用JSTL

JSP中,EL表示式是個很方便的工具,但是EL表示式功能很有限制(例如不能遍歷集合等)JSTL作為最基本的標籤庫,JSTL庫中提供了一系列的JSP標籤,實現了最基本的功能,例如集合的遍歷、資料的輸出、字串的處理、資料的格式化等。

二、JSTL的構成

JSTL包括corefntsqlXML4個標籤庫,以及一個fn方法庫。在Java EE 1.4之前,JSP中使用JSTL需要新增JSTL的類庫,從Java EE 5

開始,內建JSTL的支援,可以直接使用。

三、JSTLcore標籤庫

Core標籤庫是JSTL的核心標籤庫,或者說是基本標籤庫,實現了最基本的功能。在使用core標籤庫下的標籤時,需要在JSP檔案中引入標籤庫,如:<%@ taglib uri=”http://java.sun.com/jsp/jstl/core” prefix=”c”%>

以下為core標籤庫下各主要標籤的使用介紹:

1<c:out/>標籤:JSTL中使用out標籤輸出資料。

<c:out value=”${param.action}”></c:out>

注:out標籤還有另外兩個屬性:

defaultescapeXml。如果value屬性的值不存在,會輸出default屬性的值。如果excapeXmltrue,則會對輸出的內容進行XML編碼。

2<c:if/>標籤條件判斷的標籤,判斷條件寫在test屬性中。

<c:if test=”${param.action == “add”}”>

……..

</c:if>

<c:if test=”${param.action == “edit”}”>

……..

</c:if>

3<c:choose/><c:when/><c:otherwise>

標籤

<c:choose>

<c:when test=”${param.aciton}”>

When標籤輸出

</c:when>

<c:otherwise>

Otherwise標籤輸出

</c:otherwise>
</c:choose>

4<c:forEach/>標籤為迴圈標籤,items屬性裡是集合類物件或者是陣列。

顯示偶數:

<c:forEach var=”num” begin=”2” end=”100” step=”2”>

<div>${num}</div>

</c:forEach>

遍歷List

<c:forEach istem=”${personList}” var=”person”>

<tr>

<td>${person.id}</td>

<td>${person.name}</td>

<td>${person.age}</td>

<td>${person.sex}</td>

<td>${person.city}</td>

<td>${person.birthday}</td>

</tr>

</c:forEach>

遍歷Map物件:

<c:forEach var=”item” items=”${header}”>

<tr>

<td>${item.key}</td>

<td>${item.value}</td>

</tr>

</c:forEach>

<c:forEach>標籤的varStatus屬性可以實現隔行變色的功能。如下:

<c:forEach item=”${persoinList}” vae=”person” varStatus=”varStatus”>

<tr bgcolor=”${varStatus.index % 2 == 1 ? ‘#EFEFEF’ : ‘#FFFFFF’}”>

<td>${varStatus.current.id}</td>

…………

</tr>

</c:forEach>

注:varStatus的屬性:indexcountfistlastcurrentbeginendstep

5<c:forTokens/>標籤為迴圈標籤,items屬性裡面是字串,會被delims屬性分割成多個字串,forTokens就是遍歷這些字串。

<c:forTokens items=”Jane,Tomi,Andy,Hedrix,McCarteny,Lenno,Court,Ben” delims=”,” var=”item” varStatus=”varStatus” begin=”1” end=”7” step=”2”>

<tr>

<td>${varStatus.index}</td>

<td>${item}</td>

</tr>

</c:forTokens>

6<c:set/>實現計數器,set標籤既可以宣告一個不存在的物件,也可以修改一個已經存在的物件,還可以只修改該物件的某個屬性,前提是該屬性是可寫的(即有對應的setter方法)

<c:set var=”totalCount” value=”${totalCount + 1}” scope=”application”></c:set>

<c:set var=”count” value=”${count + 1}” scope=”session”></c:set>

本網站總訪問人數:${totalCount} <br/>

其中您的訪問次數:${count} <br/>

注:target作用類似於var,不同的是target只能用來操作Java Bean或者Maptarget只能修改已存在的Java Bean的屬性或者Map的內容,而不能建立,因此如果targetnull,會丟擲異常。Targetvar二者不能同時使用。

7<c:remove/>標籤與set標籤作用正好相反。可以從pagerequestsessionapplication等刪除所有型別的資料。

<% request.setAttribute(“somemap”, new HashMap()); %>

<c:remove var=”somemap” />

${somemap == null ? ‘somemap 已經被刪除’ : ‘somemap 沒有被刪除’}

8<c:catch/>捕捉異常

<c:catch var=”e”>

<c:set target=”someBean” property=”someProperty” value=”Some Value”>

</c:set>

</c:catch>

<c:if test=”${e != null}”>

程式丟擲了異常${e.class.name},原因:${e.message}

</c:if>

9<c:import/>匯入網路資源

<c:import var=”baidu” url=”http://www.baidu.com” charEncoding=”gbk” cope=”request”/>

Baidu的原始碼為:<br/><br/>

<c:out value=”${ baidu}” escapeXml=”true”></c:out>

10<c:url/>標籤,JSP中,如果客戶瀏覽器不支援Cookie,則可以使用request.encodeURL()方法對URL進行編碼,使該客戶也能使用Session功能,這叫做URL重寫。url標籤的作用就是實現類似功能。

<c:url value=”/images/bg.gif”>

11<c:redirect/>標籤用於實現Redirect重定向功能。

<c:redirect url=”http://www.baidu.com” ></c:redirect>

12<c:param/>標籤,有時候重定向到頁面需要引數,這時候可以配合param標籤一塊使用。Param標籤專門用於設定引數。

<c:redirect url=”http://www.baidu.com” >

<c:param name=”wd” value=”音樂”></c:param>

<c:param name=”cl” value=”3”></c:param>

</c:redirect>

四、JSTLfnt標籤庫

Fnt的標籤為輔助性功能標籤。Fnt英文全稱為format。在使用fnt標籤庫下的標籤時,需要在JSP檔案中引入標籤庫,如:<%@ taglib uri=”http://java.sun.com/jsp/jstl/fnt” prefix=”fnt”%>

以下為fnt標籤庫下各主要標籤的使用介紹:

1<fnt:requestEncoding/>設定編碼

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

2<fmt:setLocale/>顯示所有地區的資料格式,用於設定Locale

<fmt:setLocale value=”${locale}”/>

3<fmt:timeZone/>顯示全球時間,Locale只是影響到時間的格式,TimeZone會影響到時間的值,timeZone標籤只對標籤內的程式碼有效。

<fmt:timeZone value=”Asia/Shanghai”>

中間為timeZone標籤生效的作用域

</fmt:timeZone>

4<fmt:setTimeZone>設定時區,如果需要設定全域性的Time Zone,需要使用setTimeZon標籤。

5<fmt:bundle/><fmt:message/><fmt:param/>資源國際化

Java中使用ResourceBundle類解決i18n(國際化)的問題,把所有的中文提示都放在messages_zh_CN.properties檔案中。JSTL提供了bundle標籤,message標籤與param標籤來實現該功能。

<fmt:bundle basename=”messages”>

<fmt:message key=”prompt.hello”>

<fmt:param value=”yiyu986”></fmt:param>

</fmt:message> <br/>

<fmt:message key=”prompt.greeting”></fmt:message>

</fmt:bundle>

6<fmt:setBundle/>標籤,bundle標籤只對標籤內部的message標籤有效,而setBundle標籤對所有的message標籤有效。

<fmt:setBundle basename=”message” var=”resource” scope=”request”/>

<fmt:message bundle=”{resource}” key=”prompt.hello”>

<fmt:param>yiyu986</fmt:param>

</fmt:message>

<fmt:message bundle=”${resource}” key=”prompt.greeting”></fmt:message>

7<fmt:formatNumber/>顯示不同地區的各種資料格式,formatNumber標籤能夠根據不同的Locale輸出不同的格式。

8<fmt:parseNumber/>解析數字,parseNumber標籤與formatNumber標籤功能剛好相反,formatNumber把數字轉為字串,parseNumber標籤把字串轉為數字。

<fmt:parseNumber value=”1,000”></fmt:parseNumber> <br/>

<fmt:parseNumber value=”1,000” parseLocale=”de”></fmt:parseNumber> </br>

9<fmt:formatDate/>格式化日期,用於將日期格式化為指定格式的字串。

<jsp:useBean id=”currDate” class=”java.util.Date”></jsp:useBean>

<fmt:formatDate value=”${currDate}” />

<fmt:formatDate value=”${currDate}” pattern=”yyyy/MM/dd HH:mm:ss:sss”>

</fmt:formatDate>

10<fmt:parseDate/>解析日期,將字串轉化為時間

<fmt:parseDate value=”2008-12-12”></fmt:parseDate>

<fmt:parseDate value=”2008-12-12 08:00:00” pattern=”yyyy-MM-dd HH:mm:ss” parseLocale=”ja”>

</fmt:parseDate>

<fmt:formatDate value=”${date}” type=”both” dateStyle=”full” timeStyle=”full” timeZone=”America/Los_Angeles” />

五、JSTLfn方法庫

Fn的全稱為functions。就是提供一些方法、函式等。Fn使用起來不像前面的corefnt標籤那樣遵循<prefix:tagName/>格式,而是遵循fn:methodName()格式。在使用fn方法庫下的方法時,需要在JSP檔案中引入標籤庫,如:<%@ taglib uri=”http://java.sun.com/jsp/jstl/functions” prefix=”fn”%>

以下為fn方法庫下各主要標籤的使用介紹:

1、fn:contains()顯示使用者瀏覽器、作業系統。

<c:if test=”${ fn:contains(header[‘User-Agent’], ‘MSIE’)}”>IE瀏覽器</c:if>

2、fn:containsIgnoreCase()方法,可以使用該方法忽略大小寫。

<c:if test=”${ fn:containsIgnoreCase(header[‘User-Agent’], ‘Windows’)}”>Window作業系統</c:if>

3、fn:endsWith()顯示檔案格式,endsWith()方法判斷某字串是否以指定的引數結尾。

<c:if test=”${fn:endsWith(file.name, ‘.jpg’)}”>JPG圖片</c:if>

4、fn:startsWith()方法用於判斷某字串是否以指定的引數開始。

5、fn:escapXml()實現HTML編碼,使用者對XMLHTML字元(例如“&”,“<”,“>”,英文引號等)進行編碼。作用同<c:out value=”” escapeXml=”true”>,out標籤只能輸出而不能儲存到某變數中,因此如果需要編碼並且輸出到某個變數中,escapeXml()方法是個不錯的選擇。

<c:import var=”source” url=”http://www.baidu.com” charEncoding=”gbk”></c:import>

<c:out value=”${source}” escapeXml=”true”></c:out> <hr/>

${ fn:escapeXml(source) } <hr>

6、fn:indexOf()方法用於查詢字串在另一個字串中第一次出現的位置,如果沒有,則返回-1

Fn:indexOf(‘filename.txt’, ‘.’) = ${ fn:indexOf(‘filename.txt’, ‘.’) }

7、fn:split()分割字元,將字串以指定引數為界分割成多個字串。

<c:set value=”${ fn:split(header[‘accept’], ‘,’)}” var=”names” />

Header[‘accept’]: <br/><br/>

<c:forEach items=”${ names }” var=”name”>

${name} <br/>

</c:forEach>

8、fn:join()聯合字元,與split方法剛好相反,split是將字串切割成字串陣列,而join是將字串陣列以引數為界連結成字串。

<%

Request.setAttribute(“array”, new String[]{“John”, “Tom”, “Tommi”, “Kurt”});

%>

${ fn:join(array, “; ”) }

9、fn:length()方法可以取字串、陣列、集合的長度。

“${ pageContext.request.requestURL}”的長度:${ fn:length(pageContext.request.requestURI) } <br/>

Cookie[]的長度:${ fn:length(header) } <br/>

六、JSTLSQL標籤庫

JSTL可以直接操作資料庫,SQL標籤庫提供了對資料庫相關操作的支援。在使用SQL標籤庫下的標籤時,需要在JSP檔案中引入標籤庫,如:<%@ taglib uri=”http://java.sun.com/jsp/jstl/sql” prefix=”sql”%>

以下為sql標籤庫下各主要標籤的使用介紹:

1<sql:setDataSource>設定資料來源,用於生成一個數據源,需要指定JDBC驅動、資料庫連線池URL、資料庫使用者名稱和密碼等。

<sql:setDataSource driver=”com.mysql.jdbc.Driver”

use=”root”

password=”yiyu986”

url=”jdbc.mysql://localhost:3306/jstl?charachterEncoding=UTF-8”

var=”dataSource”

scope=”page” />
資料來源:${ dataSource.class.name}

2<sql:query/>查詢表資料,通過query標籤查詢資料庫。

<sql:query var=”rs” dataSource=”${ dataSource }” scope=”page”>

Select * from tb_corporation

</sql:query>

<c:forEach var=”row” items=”${ rs.rows }”>

<tr>

<td>${ row[‘id’] }</td>

<td>${ row[‘name’] }</td>

<td>${ row[‘description’] }</td>

</tr>

</c:forEach>

或者:

<sql:query var=”rs” dataSource=”${ dataSource }” scope=”page” sql=” Select * from tb_corporation”>

</sql:query>

3<sql:query/>分頁顯示,分頁顯示需要查找出記錄總數,然後根據每頁都記錄數計算startRowmaxRow,然後再查詢資料。

4<sql:query/>結果集的動態遍歷,query標籤結果集提供了一個columnNames的屬性,${rs.columnNames}將返回所有的列名。利用返回值的這個屬性就可以動態的遍歷任何一個結果集。

5<sql:update/>更新表資料,用於執行SQL更新資料,該標籤返回int型別的資料,儲存到var宣告的變數中。可以執行多種SQL,如:CREATE TABLEDROP TABLEINSERTDELETEUPDATE等。

<sql:update var=”result” dataSource=”${ dataSource }”>

Drop table if exits tb_corporation

</sql:update>

6<sql:param/><sql:dateParam/>設定日期引數,使用引數時需要使用param標籤與dateParam標籤設定引數。Param標籤可以設定Stringint等型別資料,dateParam可以設定Date型別資料。

<sql:update dataSource=”${ dataSource }”>

Insert into tb_person(name, birthday) value (?, ?)

<sql:param value=”yiyu986”></sql:param>

<sql:dateParam value=”${ date }” type=”timestamp” />

<sql:update>

7<sql:transaction/>事務管理,JSTL中也有事務性支援,transaction標籤內的程式碼為一個事務。

<c:catch var=”e”>

<sql:transaction dataSource=”${ dataSource }”>

<c:forEach var=”i” begin=”1” end=”3”>

<sql:update var=”result”>

Insert into tb_corporation (name, description) values (‘事務測試’, ‘事務測試’)

</sql:update> <br/>

</c:forEach>

<sql:update var=”result”>
insert into tb_corporation (id, name, description) values (1, ‘
事務測’,‘事務測試’)

</sql:update>

</sql:transaction>

</c:catch>

七、JSTLXML標籤庫

JSTL有專門的XML標籤庫提供對XML檔案解析的支援。使用JSTLXML標籤,除了需要jstl.jarstandard.jar之外,還需要xalan.jarserializer.jar包,否則執行時會出錯。另外XML標籤的字首不能使用XML,因為<XML/>是被保留的,習慣上使用x作為標籤的字首,例如<x:parse/>。在使用XML標籤庫下的標籤時,需要在JSP檔案中引入標籤庫,如:<%@ taglib uri=”http://java.sun.com/jsp/jstl/XML” prefix=”x”%>

以下為xml標籤庫下各主要標籤的使用介紹:

1<x:parse/>標籤用來解析一個XML檔案,只需要將XML內容放入parse標籤內即可。

<x:parse var=”content”>

<student description=”Software Engineer”>

<name>yiyu986</name>

<age>20</age>

</student>

</x:parse>

或者:

<c:set var=”XML”>

<student description=”Software Engineer”>

<name>yiyu986</name>

<age>20</age>

</student>

</c:set>

<c:parse var=”content” doc=”${ XML }” />

更多的時候parse標籤是與core標籤庫的import標籤一塊連用的。Import匯入一個XML檔案,傳給