Java for Web學習筆記(二五):JSTL(1)使用JSTL
在前面已經使用過JSTL,例如<c:url>,fn是JSTL的functionlibrary,而c是JSTL的tag library。使用它們,我們要告知解析器,如下:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
這些directive相當於下面的。雖然prefix(或者說namespace)可以設定為不同,但是我們應當遵循TLD(Tag Library Descriptor)中的建議,方便其他人閱讀。
<jsp:root xmlns="http://www.w3.org/1999/xhtml" version="2.0"
xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:fn="http://java.sun.com/jsp/jstl/functions">
在JSP檔案中,jsp tag是預設預設的,即無需給出prefix(namespace),當然,也可以寫為<jsp:include>,<jsp:forward>。
注意,uri是名字的約定,而不是真正的網址,只是用於作為TLD的唯一標識。當JSP解析器碰到taglib的directive,需使用URI獲得該tag library的TLD檔案。解析器首先搜尋Java EE容器的Jave EE specification的TLD檔案,包括JSP taglibrary,JSTL,和JavaServer Faces libraries;其次檢查在web.xml中在<jsp-config>中指定的<taglib>;再其次檢查應用/WEB-INF/lib中的JAR檔案是否還有TLD檔案,或者在/WEB-INF下或其子目錄下的TLD檔案;最後檢查是否作為web容器或者應用伺服器部分進行了封裝的TLD(此通常是自定義的web容器,使得應用和web容器繫結,無法移植)。
對於第二種的自定義方式,如下:
<jsp-config>
...
<taglib>
<taglib-uri>http://www.example.org/xmlns/jsp/custom</taglib-uri>
<taglib-location>/tld/custom.tld</taglib-location>
</taglib>
...
</jsp-config>
Tomcat Server並不支援JSTL,因此在Maven的pom.xml檔案中需要引入,採用lib的jar方式提供JSTL的支援。注意,這裡的<scope>採用的是compile而不是provided,因為tomcat並不包含相關的libraries。
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>1.2.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.servlet.jsp.jstl</artifactId>
<version>1.2.2</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
<exclusion>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
</exclusion>
<exclusion>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
</exclusion>
</exclusions>
</dependency>
JSTL裡面有5個tag庫,分佈是:
- Core(c)
- Formatting(fmt)
- Functions(fn)
- SQL(sql)
- XML(x)