JSTL 標籤大全詳解




(尊重勞動成果,轉載請註明出處:http://blog.csdn.NET/qq_25827845/article/details/53311722  冷血之心的博客)


一、JSTL標籤介紹


1、什麼是JSTL?

        JSTL是apache對EL表達式的擴展(也就是說JSTL依賴EL),JSTL是標籤語言!JSTL標籤使用以來非常方便,它與JSP動作標籤一樣,只不過它不是JSP內置的標籤,需要我們自己導包,以及指定標籤庫而已!

       如果你使用MyEclipse開發JavaWeb,那麼在把項目發佈到Tomcat時,你會發現,MyEclipse會在lib目錄下存放jstl的Jar包!如果你沒有使用MyEclipse開發那麼需要自己來導入這個JSTL的Jar包:jstl-1.2.jar。



2、JSTL標籤庫:

JSTL一共包含四大標籤庫:

  • core:核心標籤庫,我們學習的重點;
  • fmt:格式化標籤庫,只需要學習兩個標籤即可;
  • sql:數據庫標籤庫,不需要學習了,它過時了;
  • xml:xml標籤庫,不需要學習了,它過時了。



3、使用taglib指令導入標籤庫:

除了JSP動作標籤外,使用其他第三方的標籤庫都需要:

  • 導包;
  • 在使用標籤的JSP頁面中使用taglib指令導入標籤庫;

下面是導入JSTL的core標籤庫:

[html] view plain copy
  1. <%@ taglib prefix="c"uri="http://java.sun.com/jstl/core" %>  

  • prefix="c":指定標籤庫的前綴,這個前綴可以隨便給值,但大家都會在使用core標籤庫時指定前綴爲c;
  • uri="http://java.sun.com/jstl/core":指定標籤庫的uri,它不一定是真實存在的網址,但它可以讓JSP找到標籤庫的描述文件;


4、core標籤庫常用標籤:

(1)out和set標籤

<c:out value=”aaa”/>

輸出aaa字符串常量

<c:out value=”${aaa}”/>

與${aaa}相同

<c:out value=”${aaa}” default=”xxx”/>

當${aaa}不存在時,輸出xxx字符串

<%

request.setAttribute("a","<script>alert('hello');</script>");

%>

<c:out value="${a }" default="xxx" escapeXml="false" />

當escapeXml爲false,不會轉換“<”、“>”。這可能會受到JavaScript攻擊。


<c:set var=”a” value=”hello”/>

    在pageContext中添加name爲a,value爲hello的數據。

<c:set var=”a” value=”hello” scope=”session”/>

在session中添加name爲a,value爲hello的數據。

 


(2)remove標籤

<%

                   pageContext.setAttribute("a","pageContext");

                   request.setAttribute("a","session");

                   session.setAttribute("a","session");

                   application.setAttribute("a","application");

  %>

    <c: remove var="a"/>

    <c: out value="${a}" default="none"/>

刪除所有域中name爲a的數據!
<c:remove var="a" scope=”page”/> 刪除pageContext中name爲a的數據 


(3)url標籤:該標籤會在需要重寫URL時添加。

<c:url value="/"/>

     輸出上下文路徑:/項目名/

<c:url value="/" var="a" scope="request"/>

    把本該輸出的結果賦給變量a。範圍爲request

<c:url value="/AServlet"/>

     輸出:/項目名/AServlet

<c:url value="/AServlet">

<c:param name="username" value="abc"/>

<c:param name="password" value="123"/>                   

     輸出:/項目名/AServlet?username=abc&password=123

     如果參數中包含中文,那麼會自動使用URL編碼!                       



(4)if標籤:

if標籤的test屬性必須是一個boolean類型的值,如果test的值爲true,那麼執行if標籤的內容,否則不執行。


[html] view plain copy
  1. <c:set var="a" value="hello"/>  
  2. <c:if test="${not empty a }">  
  3.     <c:out value="${a }"/>  
  4. </c:if>  

(5)choose標籤:

choose標籤對應Java中的if/else if/else結構。when標籤的test爲true時,會執行這個when的內容。當所有when標籤的test都爲false時,纔會執行otherwise標籤的內容。

[html] view plain copy
  1. <c:set var="score" value="${param.score }"/>  
  2. <c:choose>  
  3.     <c:when test="${score > 100 || score < 0}">錯誤的分數:${score }</c:when>  
  4.     <c:when test="${score >= 90 }">A級</c:when>  
  5.     <c:when test="${score >= 80 }">B級</c:when>  
  6.     <c:when test="${score >= 70 }">C級</c:when>  
  7.     <c:when test="${score >= 60 }">D級</c:when>  
  8.     <c:otherwise>E級</c:otherwise>  
  9. </c:choose>  


(6)forEach標籤:

forEach當前就是循環標籤了,forEach標籤有多種兩種使用方式:

  • 使用循環變量,指定開始和結束值,類似for(int i = 1; i <= 10; i++) {};
  • 循環遍歷集合,類似for(Object o : 集合);

循環變量:

[html] view plain copy
  1. <c:set var="sum" value="0" />   
  2. <c:forEach var="i" begin="1" end="10">   
  3.     <c:set var="sum" value="${sum + i}" />   
  4. </c:forEach>  
  5. <c:out value="sum = ${sum }"/>  
  6. <c:set var="sum" value="0" />  
  7. <c:forEach var="i" begin="1" end="10" step ="2">  
  8.     <c:set var="sum" value="${sum + i}" />  
  9. </c:forEach>  
  10. <c:out value="sum = ${sum }"/>  

遍歷集合或數組方式:

[html] view plain copy
  1. <%  
  2. String[] names = {"zhangSan", "liSi", "wangWu", "zhaoLiu"};  
  3. pageContext.setAttribute("ns", names);  
  4. %>  
  5. <c:forEach var="item" items="${ns }">  
  6.     <c:out value="name: ${item }"/><br/>  
  7. </c:forEach>  

遍歷List:

[html] view plain copy
  1. <%  
  2.     List<String> names = new ArrayList<String>();  
  3.     names.add("zhangSan");  
  4.     names.add("liSi");  
  5.     names.add("wangWu");  
  6.     names.add("zhaoLiu");  
  7.     pageContext.setAttribute("ns", names);  
  8. %>  
  9. <c:forEach var="item" items="${ns }">  
  10.     <c:out value="name: ${item }"/><br/>  
  11. </c:forEach>  



遍歷Map:

[html] view plain copy
  1. <%  
  2.     Map<String,String> stu = new LinkedHashMap<String,String>();  
  3.     stu.put("number", "N_1001");  
  4.     stu.put("name", "zhangSan");  
  5.     stu.put("age", "23");  
  6.     stu.put("sex", "male");  
  7.     pageContext.setAttribute("stu", stu);  
  8. %>  
  9. <c:forEach var="item" items="${stu }">  
  10.     <c:out value="${item.key }: ${item.value }"/><br/>  
  11. </c:forEach>  

forEach標籤還有一個屬性:varStatus,這個屬性用來指定接收“循環狀態”的變量名,例如:<forEach varStatus=”vs” …/>,這時就可以使用vs這個變量來獲取循環的狀態了。

  • count:int類型,當前以遍歷元素的個數;
  • index:int類型,當前元素的下標;
  • first:boolean類型,是否爲第一個元素;
  • last:boolean類型,是否爲最後一個元素;
  • current:Object類型,表示當前項目。

[html] view plain copy
  1. <c:forEach var="item" items="${ns }" varStatus="vs">  
  2.     <c:if test="${vs.first }">第一行:</c:if>  
  3.     <c:if test="${vs.last }">最後一行:</c:if>  
  4.     <c:out value="第${vs.count }行: "/>  
  5.     <c:out value="[${vs.index }]: "/>  
  6.     <c:out value="name: ${vs.current }"/><br/>  
  7. </c:forEach>  


5、fmt標籤庫常用標籤:

      fmt標籤庫是用來格式化輸出的,通常需要格式化的有時間和數字。

格式化時間:

[html] view plain copy
  1. <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>  
  2. ......  
  3. <%  
  4.     Date date = new Date();  
  5.     pageContext.setAttribute("d", date);  
  6. %>  
  7. <fmt:formatDate value="${d }" pattern="yyyy-MM-dd HH:mm:ss"/>  

格式化數字:

[html] view plain copy
  1. <%  
  2.     double d1 = 3.5;  
  3.     double d2 = 4.4;   
  4.     pageContext.setAttribute("d1", d1);  
  5.     pageContext.setAttribute("d2", d2);  
  6. %>  
  7. <fmt:formatNumber value="${d1 }" pattern="0.00"/><br/>  
  8. <fmt:formatNumber value="${d2 }" pattern="#.##"/>  


介紹了JSTL中的常用標籤,那可以定義自己的標籤嗎?

答案是:可以。


二、自定義標籤


1、自定義標籤


1.1步驟:

其實我們在JSP頁面中使用標籤就等於調用某個對象的某個方法一樣,例如:<c:if test=””>,這就是在調用對象的方法一樣。自定義標籤其實就是自定義類一樣!

  • 定義標籤處理類:必須是Tag或SimpleTag的實現類;
  • 編寫標籤庫描述符文件(TLD);

  SimpleTag接口是JSP2.0中新給出的接口,用來簡化自定義標籤,所以現在我們基本上都是使用SimpleTag。

Tag是老的,傳統的自定義標籤時使用的接口,現在不建議使用它了。

 

1.2 SimpleTag接口介紹:

SimpleTag接口內容如下:

  • void doTag():標籤執行方法;
  • JspTag getParent():獲取父標籤;
  • void setParent(JspTag parent):設置父標籤
  • void setJspContext(JspContext context):設置PageContext
  • void setJspBody(JspFragment jspBody):設置標籤體對象;

 

請記住,萬物皆對象!在JSP頁面中的標籤也是對象!你可以通過查看JSP的源碼,清楚的知道,所有標籤都會變成對象的方法調用。標籤對應的類我們稱之爲“標籤處理類”!

標籤的生命週期:

1、當容器(Tomcat)第一次執行到某個標籤時,會創建標籤處理類的實例;

2、然後調用setJspContext(JspContext)方法,把當前JSP頁面的pageContext對象傳遞給這個方法;

3、如果當前標籤有父標籤,那麼使用父標籤的標籤處理類對象調用setParent(JspTag)方法;

4、如果標籤有標籤體,那麼把標籤體轉換成JspFragment對象,然後調用setJspBody()方法;

5、每次執行標籤時,都調用doTag()方法,它是標籤處理方法


HelloTag.java

[java] view plain copy
  1. public class HelloTag implements SimpleTag {  
  2.     private JspTag parent;  
  3.     private PageContext pageContext;  
  4.     private JspFragment jspBody;  
  5.       
  6.     public void doTag() throws JspException, IOException {  
  7.         pageContext.getOut().print("Hello Tag!!!");  
  8.     }  
  9.     public void setParent(JspTag parent) {  
  10.         this.parent = parent;  
  11.     }  
  12.     public JspTag getParent() {  
  13.         return this.parent;  
  14.     }  
  15.     public void setJspContext(JspContext pc) {  
  16.         this.pageContext = (PageContext) pc;  
  17.     }  
  18.     public void setJspBody(JspFragment jspBody) {  
  19.         this.jspBody = jspBody;  
  20.     }  
  21. }  

1.3 標籤庫描述文件(TLD)

標籤庫描述文件是用來描述當前標籤庫中的標籤的!標籤庫描述文件的擴展名爲tld,你可以把它放到WEB-INF下,這樣就不會被客戶端直接訪問到了。


hello.tld

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee"  
  3.     xmlns:xml="http://www.w3.org/XML/1998/namespace"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
  6.                         http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd ">  
  7.   
  8.     <tlib-version>1.0</tlib-version>  
  9.     <short-name>ywq</short-name>  
  10.     <uri>http://www.ywq.cn/tags</uri>  
  11.     <tag>  
  12.         <name>hello</name>  
  13.         <tag-class>cn.ywq.tag.HelloTag</tag-class>  
  14.         <body-content>empty</body-content>  
  15.     </tag>  
  16. </taglib>  


1.4 使用標籤

在頁面中使用標籤分爲兩步:

  • 使用taglib導入標籤庫;
  • 使用標籤;

[html] view plain copy
  1. <%@ taglib prefix="it" uri="/WEB-INF/hello.tld" %>  
  2. ......  
  3. <it:hello/>  



2、自定義標籤進階


2.1 繼承SimpleTagSupport

  繼承SimpleTagSuppport要比實現SimpleTag接口方便太多了,現在你只需要重寫doTag()方法,其他方法都已經被SimpleTagSuppport完成了。

[java] view plain copy
  1. public class HelloTag extends SimpleTagSupport {  
  2.     public void doTag() throws JspException, IOException {  
  3.         this.getJspContext().getOut().write("<p>Hello SimpleTag!</p>");  
  4.     }  
  5. }  

2.2 有標籤體的標籤

我們先來看看標籤體內容的可選值:

<body-content>元素的可選值有:

  • empty:無標籤體。
  • JSP:傳統標籤支持它,SimpleTag已經不再支持使用<body-content>JSP</body-content>。標籤體內容可以是任何東西:EL、JSTL、<%=%>、<%%>,以及html;
  • scriptless:標籤體內容不能是Java腳本,但可以是EL、JSTL等。在SimpleTag中,如果需要有標籤體,那麼就使用該選項
  • tagdependent:標籤體內容不做運算,由標籤處理類自行處理,無論標籤體內容是EL、JSP、JSTL,都不會做運算。這個選項幾乎沒有人會使用!

 

自定義有標籤體的標籤需要:

  • 獲取標籤體對象:JspFragment jspBody = getJspBody();;
  • 把標籤體內容輸出到頁面:jspBody.invoke(null);
  • tld中指定標籤內容類型:scriptless。

[java] view plain copy
  1. public class HelloTag extends SimpleTagSupport {  
  2.     public void doTag() throws JspException, IOException {  
  3.         PageContext pc = (PageContext) this.getJspContext();  
  4.         HttpServletRequest req = (HttpServletRequest) pc.getRequest();  
  5.         String s = req.getParameter("exec");  
  6.         if(s != null && s.endsWith("true")) {  
  7.             JspFragment body = this.getJspBody();  
  8.             body.invoke(null);  
  9.         }  
  10.     }  
  11. }  

[html] view plain copy
  1. <tag>  
  2.         <name>hello</name>  
  3.         <tag-class>cn.ywq.tags.HelloTag</tag-class>  
  4.         <body-content>scriptless</body-content>  
  5.     </tag>  


[html] view plain copy
  1. <itcast:hello>  
  2.         <h1>哈哈哈~</h1>  
  3.    </itcast:hello>  

2.3 不執行標籤下面的頁面內容

  如果希望在執行了自定義標籤後,不再執行JSP頁面下面的東西,那麼就需要在doTag()方法中使用SkipPageException。

[java] view plain copy
  1. public class SkipTag extends SimpleTagSupport {  
  2.     public void doTag() throws JspException, IOException {  
  3.         this.getJspContext().getOut().print("<h1>只能看到我!</h1>");  
  4.         throw new SkipPageException();  
  5.     }  
  6. }  

[html] view plain copy
  1. <tag>  
  2.     <name>skip</name>  
  3.     <tag-class>cn.ywq.tags.SkipTag</tag-class>  
  4.     <body-content>empty</body-content>  
  5. </tag>  
[html] view plain copy
  1. <itcast:skip/>  
  2. <h1>看不見我!</h1>  


2.4 帶有屬性的標籤

一般標籤都會帶有屬性,例如<c:iftest=””>,其中test就是一個boolean類型的屬性。完成帶有屬性的標籤需要:

  • 在處理類中給出JavaBean屬性(提供get/set方法);
  • 在TLD中部屬相關屬性。

[java] view plain copy
  1. public class IfTag extends SimpleTagSupport {  
  2.     private boolean test;  
  3.     public boolean isTest() {  
  4.         return test;  
  5.     }  
  6.     public void setTest(boolean test) {  
  7.         this.test = test;  
  8.     }  
  9.     @Override  
  10.     public void doTag() throws JspException, IOException {  
  11.         if(test) {  
  12.             this.getJspBody().invoke(null);  
  13.         }  
  14.     }  
  15. }  

[html] view plain copy
  1. <tag>   
  2.         <name>if</name>   
  3.         <tag-class>cn.ywq.IfTag</tag-class>   
  4.         <body-content>scriptless</body-content>  
  5.         <attribute>  
  6.             <name>test</name>  
  7.             <required>true</required>  
  8.             <rtexprvalue>true</rtexprvalue>  
  9.         </attribute>   
  10.     </tag>  

[html] view plain copy
  1. <%  
  2.     pageContext.setAttribute("one", true);  
  3.     pageContext.setAttribute("two", false);  
  4. %>  
  5. <it:if test="${one }">xixi</it:if>  
  6. <it:if test="${two }">haha</it:if>  
  7. <it:if test="true">hehe</it:if>  


關於JSTL標籤相關內容就到這裏了,如果對你有幫助,記得點贊哦~歡迎大家關注我的博客,可以進羣366533258一起交流學習哦~



(尊重勞動成果,轉載請註明出處:http://blog.csdn.NET/qq_25827845/article/details/53311722  冷血之心的博客)


一、JSTL標籤介紹


1、什麼是JSTL?

        JSTL是apache對EL表達式的擴展(也就是說JSTL依賴EL),JSTL是標籤語言!JSTL標籤使用以來非常方便,它與JSP動作標籤一樣,只不過它不是JSP內置的標籤,需要我們自己導包,以及指定標籤庫而已!

       如果你使用MyEclipse開發JavaWeb,那麼在把項目發佈到Tomcat時,你會發現,MyEclipse會在lib目錄下存放jstl的Jar包!如果你沒有使用MyEclipse開發那麼需要自己來導入這個JSTL的Jar包:jstl-1.2.jar。



2、JSTL標籤庫:

JSTL一共包含四大標籤庫:

  • core:核心標籤庫,我們學習的重點;
  • fmt:格式化標籤庫,只需要學習兩個標籤即可;
  • sql:數據庫標籤庫,不需要學習了,它過時了;
  • xml:xml標籤庫,不需要學習了,它過時了。



3、使用taglib指令導入標籤庫:

除了JSP動作標籤外,使用其他第三方的標籤庫都需要:

  • 導包;
  • 在使用標籤的JSP頁面中使用taglib指令導入標籤庫;

下面是導入JSTL的core標籤庫:

[html] view plain copy
  1. <%@ taglib prefix="c"uri="http://java.sun.com/jstl/core" %>  

  • prefix="c":指定標籤庫的前綴,這個前綴可以隨便給值,但大家都會在使用core標籤庫時指定前綴爲c;
  • uri="http://java.sun.com/jstl/core":指定標籤庫的uri,它不一定是真實存在的網址,但它可以讓JSP找到標籤庫的描述文件;


4、core標籤庫常用標籤:

(1)out和set標籤

<c:out value=”aaa”/>

輸出aaa字符串常量

<c:out value=”${aaa}”/>

與${aaa}相同

<c:out value=”${aaa}” default=”xxx”/>

當${aaa}不存在時,輸出xxx字符串

<%

request.setAttribute("a","<script>alert('hello');</script>");

%>

<c:out value="${a }" default="xxx" escapeXml="false" />

當escapeXml爲false,不會轉換“<”、“>”。這可能會受到JavaScript攻擊。


<c:set var=”a” value=”hello”/>

    在pageContext中添加name爲a,value爲hello的數據。

<c:set var=”a” value=”hello” scope=”session”/>

在session中添加name爲a,value爲hello的數據。

 


(2)remove標籤

<%

                   pageContext.setAttribute("a","pageContext");

                   request.setAttribute("a","session");

                   session.setAttribute("a","session");

                   application.setAttribute("a","application");

  %>

    <c: remove var="a"/>

    <c: out value="${a}" default="none"/>

刪除所有域中name爲a的數據!
<c:remove var="a" scope=”page”/> 刪除pageContext中name爲a的數據 


(3)url標籤:該標籤會在需要重寫URL時添加。

<c:url value="/"/>

     輸出上下文路徑:/項目名/

<c:url value="/" var="a" scope="request"/>

    把本該輸出的結果賦給變量a。範圍爲request

<c:url value="/AServlet"/>

     輸出:/項目名/AServlet

<c:url value="/AServlet">

<c:param name="username" value="abc"/>

<c:param name="password" value="123"/>                   

     輸出:/項目名/AServlet?username=abc&password=123

     如果參數中包含中文,那麼會自動使用URL編碼!                       



(4)if標籤:

if標籤的test屬性必須是一個boolean類型的值,如果test的值爲true,那麼執行if標籤的內容,否則不執行。


[html] view plain copy
  1. <c:set var="a" value="hello"/>  
  2. <c:if test="${not empty a }">  
  3.     <c:out value="${a }"/>  
  4. </c:if>  

(5)choose標籤:

choose標籤對應Java中的if/else if/else結構。when標籤的test爲true時,會執行這個when的內容。當所有when標籤的test都爲false時,纔會執行otherwise標籤的內容。

[html] view plain copy
  1. <c:set var="score" value="${param.score }"/>  
  2. <c:choose>  
  3.     <c:when test="${score > 100 || score < 0}">錯誤的分數:${score }</c:when>  
  4.     <c:when test="${score >= 90 }">A級</c:when>  
  5.     <c:when test="${score >= 80 }">B級</c:when>  
  6.     <c:when test="${score >= 70 }">C級</c:when>  
  7.     <c:when test="${score >= 60 }">D級</c:when>  
  8.     <c:otherwise>E級</c:otherwise>  
  9. </c:choose>  


(6)forEach標籤:

forEach當前就是循環標籤了,forEach標籤有多種兩種使用方式:

  • 使用循環變量,指定開始和結束值,類似for(int i = 1; i <= 10; i++) {};
  • 循環遍歷集合,類似for(Object o : 集合);

循環變量:

[html] view plain copy
  1. <c:set var="sum" value="0" />   
  2. <c:forEach var="i" begin="1" end="10">   
  3.     <c:set var="sum" value="${sum + i}" />   
  4. </c:forEach>  
  5. <c:out value="sum = ${sum }"/>  
  6. <c:set var="sum" value="0" />  
  7. <c:forEach var="i" begin="1" end="10" step ="2">  
  8.     <c:set var="sum" value="${sum + i}" />  
  9. </c:forEach>  
  10. <c:out value="sum = ${sum }"/>  

遍歷集合或數組方式:

[html] view plain copy
  1. <%  
  2. String[] names = {"zhangSan", "liSi", "wangWu", "zhaoLiu"};  
  3. pageContext.setAttribute("ns", names);  
  4. %>  
  5. <c:forEach var="item" items="${ns }">  
  6.     <c:out value="name: ${item }"/><br/>  
  7. </c:forEach>  

遍歷List:

[html] view plain copy
  1. <%  
  2.     List<String> names = new ArrayList<String>();  
  3.     names.add("zhangSan");  
  4.     names.add("liSi");  
  5.     names.add("wangWu");  
  6.     names.add("zhaoLiu");  
  7.     pageContext.setAttribute("ns", names);  
  8. %>  
  9. <c:forEach var="item" items="${ns }">  
  10.     <c:out value="name: ${item }"/><br/>  
  11. </c:forEach>  



遍歷Map:

[html] view plain copy
  1. <%  
  2.     Map<String,String> stu = new LinkedHashMap<String,String>();  
  3.     stu.put("number", "N_1001");  
  4.     stu.put("name", "zhangSan");  
  5.     stu.put("age", "23");  
  6.     stu.put("sex", "male");  
  7.     pageContext.setAttribute("stu", stu);  
  8. %>  
  9. <c:forEach var="item" items="${stu }">  
  10.     <c:out value="${item.key }: ${item.value }"/><br/>  
  11. </c:forEach>  

forEach標籤還有一個屬性:varStatus,這個屬性用來指定接收“循環狀態”的變量名,例如:<forEach varStatus=”vs” …/>,這時就可以使用vs這個變量來獲取循環的狀態了。

  • count:int類型,當前以遍歷元素的個數;
  • index:int類型,當前元素的下標;
  • first:boolean類型,是否爲第一個元素;
  • last:boolean類型,是否爲最後一個元素;
  • current:Object類型,表示當前項目。

[html] view plain copy
  1. <c:forEach var="item" items="${ns }" varStatus="vs">  
  2.     <c:if test="${vs.first }">第一行:</c:if>  
  3.     <c:if test="${vs.last }">最後一行:</c:if>  
  4.     <c:out value="第${vs.count }行: "/>  
  5.     <c:out value="[${vs.index }]: "/>  
  6.     <c:out value="name: ${vs.current }"/><br/>  
  7. </c:forEach>  


5、fmt標籤庫常用標籤:

      fmt標籤庫是用來格式化輸出的,通常需要格式化的有時間和數字。

格式化時間:

[html] view plain copy
  1. <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>  
  2. ......  
  3. <%  
  4.     Date date = new Date();  
  5.     pageContext.setAttribute("d", date);  
  6. %>  
  7. <fmt:formatDate value="${d }" pattern="yyyy-MM-dd HH:mm:ss"/>  

格式化數字:

[html] view plain copy
  1. <%  
  2.     double d1 = 3.5;  
  3.     double d2 = 4.4;   
  4.     pageContext.setAttribute("d1", d1);  
  5.     pageContext.setAttribute("d2", d2);  
  6. %>  
  7. <fmt:formatNumber value="${d1 }" pattern="0.00"/><br/>  
  8. <fmt:formatNumber value="${d2 }" pattern="#.##"/>  


介紹了JSTL中的常用標籤,那可以定義自己的標籤嗎?

答案是:可以。


二、自定義標籤


1、自定義標籤


1.1步驟:

其實我們在JSP頁面中使用標籤就等於調用某個對象的某個方法一樣,例如:<c:if test=””>,這就是在調用對象的方法一樣。自定義標籤其實就是自定義類一樣!

  • 定義標籤處理類:必須是Tag或SimpleTag的實現類;
  • 編寫標籤庫描述符文件(TLD);

  SimpleTag接口是JSP2.0中新給出的接口,用來簡化自定義標籤,所以現在我們基本上都是使用SimpleTag。

Tag是老的,傳統的自定義標籤時使用的接口,現在不建議使用它了。

 

1.2 SimpleTag接口介紹:

SimpleTag接口內容如下:

  • void doTag():標籤執行方法;
  • JspTag getParent():獲取父標籤;
  • void setParent(JspTag parent):設置父標籤
  • void setJspContext(JspContext context):設置PageContext
  • void setJspBody(JspFragment jspBody):設置標籤體對象;

 

請記住,萬物皆對象!在JSP頁面中的標籤也是對象!你可以通過查看JSP的源碼,清楚的知道,所有標籤都會變成對象的方法調用。標籤對應的類我們稱之爲“標籤處理類”!

標籤的生命週期:

1、當容器(Tomcat)第一次執行到某個標籤時,會創建標籤處理類的實例;

2、然後調用setJspContext(JspContext)方法,把當前JSP頁面的pageContext對象傳遞給這個方法;

3、如果當前標籤有父標籤,那麼使用父標籤的標籤處理類對象調用setParent(JspTag)方法;

4、如果標籤有標籤體,那麼把標籤體轉換成JspFragment對象,然後調用setJspBody()方法;

5、每次執行標籤時,都調用doTag()方法,它是標籤處理方法


HelloTag.java

[java] view plain copy
  1. public class HelloTag implements SimpleTag {  
  2.     private JspTag parent;  
  3.     private PageContext pageContext;  
  4.     private JspFragment jspBody;  
  5.       
  6.     public void doTag() throws JspException, IOException {  
  7.         pageContext.getOut().print("Hello Tag!!!");  
  8.     }  
  9.     public void setParent(JspTag parent) {  
  10.         this.parent = parent;  
  11.     }  
  12.     public JspTag getParent() {  
  13.         return this.parent;  
  14.     }  
  15.     public void setJspContext(JspContext pc) {  
  16.         this.pageContext = (PageContext) pc;  
  17.     }  
  18.     public void setJspBody(JspFragment jspBody) {  
  19.         this.jspBody = jspBody;  
  20.     }  
  21. }  

1.3 標籤庫描述文件(TLD)

標籤庫描述文件是用來描述當前標籤庫中的標籤的!標籤庫描述文件的擴展名爲tld,你可以把它放到WEB-INF下,這樣就不會被客戶端直接訪問到了。


hello.tld

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee"  
  3.     xmlns:xml="http://www.w3.org/XML/1998/namespace"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
  6.                         http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd ">  
  7.   
  8.     <tlib-version>1.0</tlib-version>  
  9.     <short-name>ywq</short-name>  
  10.     <uri>http://www.ywq.cn/tags</uri>  
  11.     <tag>  
  12.         <name>hello</name>  
  13.         <tag-class>cn.ywq.tag.HelloTag</tag-class>  
  14.         <body-content>empty</body-content>  
  15.     </tag>  
  16. </taglib>  


1.4 使用標籤

在頁面中使用標籤分爲兩步:

  • 使用taglib導入標籤庫;
  • 使用標籤;

[html] view plain copy
  1. <%@ taglib prefix="it" uri="/WEB-INF/hello.tld" %>  
  2. ......  
  3. <it:hello/>  



2、自定義標籤進階


2.1 繼承SimpleTagSupport

  繼承SimpleTagSuppport要比實現SimpleTag接口方便太多了,現在你只需要重寫doTag()方法,其他方法都已經被SimpleTagSuppport完成了。

[java] view plain copy
  1. public class HelloTag extends SimpleTagSupport {  
  2.     public void doTag() throws JspException, IOException {  
  3.         this.getJspContext().getOut().write("<p>Hello SimpleTag!</p>");  
  4.     }  
  5. }  

2.2 有標籤體的標籤

我們先來看看標籤體內容的可選值:

<body-content>元素的可選值有:

  • empty:無標籤體。
  • JSP:傳統標籤支持它,SimpleTag已經不再支持使用<body-content>JSP</body-content>。標籤體內容可以是任何東西:EL、JSTL、<%=%>、<%%>,以及html;
  • scriptless:標籤體內容不能是Java腳本,但可以是EL、JSTL等。在SimpleTag中,如果需要有標籤體,那麼就使用該選項
  • tagdependent:標籤體內容不做運算,由標籤處理類自行處理,無論標籤體內容是EL、JSP、JSTL,都不會做運算。這個選項幾乎沒有人會使用!

 

自定義有標籤體的標籤需要:

  • 獲取標籤體對象:JspFragment jspBody = getJspBody();;
  • 把標籤體內容輸出到頁面:jspBody.invoke(null);
  • tld中指定標籤內容類型:scriptless。

[java] view plain copy
  1. public class HelloTag extends SimpleTagSupport {  
  2.     public void doTag() throws JspException, IOException {  
  3.         PageContext pc = (PageContext) this.getJspContext();  
  4.         HttpServletRequest req = (HttpServletRequest) pc.getRequest();  
  5.         String s = req.getParameter("exec");  
  6.         if(s != null && s.endsWith("true")) {  
  7.             JspFragment body = this.getJspBody();  
  8.             body.invoke(null);  
  9.         }  
  10.     }  
  11. }  

[html] view plain copy
  1. <tag>  
  2.         <name>hello</name>  
  3.         <tag-class>cn.ywq.tags.HelloTag</tag-class>  
  4.         <body-content>scriptless</body-content>  
  5.     </tag>  


[html] view plain copy
  1. <itcast:hello>  
  2.         <h1>哈哈哈~</h1>  
  3.    </itcast:hello>  

2.3 不執行標籤下面的頁面內容

  如果希望在執行了自定義標籤後,不再執行JSP頁面下面的東西,那麼就需要在doTag()方法中使用SkipPageException。

[java] view plain copy
  1. public class SkipTag extends SimpleTagSupport {  
  2.     public void doTag() throws JspException, IOException {  
  3.         this.getJspContext().getOut().print("<h1>只能看到我!</h1>");  
  4.         throw new SkipPageException();  
  5.     }  
  6. }  

[html] view plain copy
  1. <tag>  
  2.     <name>skip</name>  
  3.     <tag-class>cn.ywq.tags.SkipTag</tag-class>  
  4.     <body-content>empty</body-content>  
  5. </tag>  
[html] view plain copy
  1. <itcast:skip/>  
  2. <h1>看不見我!</h1>  


2.4 帶有屬性的標籤

一般標籤都會帶有屬性,例如<c:iftest=””>,其中test就是一個boolean類型的屬性。完成帶有屬性的標籤需要:

  • 在處理類中給出JavaBean屬性(提供get/set方法);
  • 在TLD中部屬相關屬性。

[java] view plain copy
  1. public class IfTag extends SimpleTagSupport {  
  2.     private boolean test;  
  3.     public boolean isTest() {  
  4.         return test;  
  5.     }  
  6.     public void setTest(boolean test) {  
  7.         this.test = test;  
  8.     }  
  9.     @Override  
  10.     public void doTag() throws JspException, IOException {  
  11.         if(test) {  
  12.             this.getJspBody().invoke(null);  
  13.         }  
  14.     }  
  15. }  

[html] view plain copy
  1. <tag>   
  2.         <name>if</name>   
  3.         <tag-class>cn.ywq.IfTag</tag-class>   
  4.         <body-content>scriptless</body-content>  
  5.         <attribute>  
  6.             <name>test</name>  
  7.             <required>true</required>  
  8.             <rtexprvalue>true</rtexprvalue>  
  9.         </attribute>   
  10.     </tag>  

[html] view plain copy
  1. <%  
  2.     pageContext.setAttribute("one", true);  
  3.     pageContext.setAttribute("two", false);  
  4. %>  
  5. <it:if test="${one }">xixi</it:if>  
  6. <it:if test="${two }">haha</it:if>  
  7. <it:if test="true">hehe</it:if>  


關於JSTL標籤相關內容就到這裏了,如果對你有幫助,記得點贊哦~歡迎大家關注我的博客,可以進羣366533258一起交流學習哦~


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章