基於JSP 自訂標籤使用執行個體介紹_JSP編程

來源:互聯網
上載者:User

添加JSP自訂標籤:

先添加一個tld檔案到WEB-INF檔案夾中
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd"
version="2.0">

<description>myTag</description>
<display-name>JSTL core</display-name>
<tlib-version>1.0</tlib-version>
<short-name>cnweb</short-name>
<uri>http://www.cnweb.cn</uri>

<tag><!-- 一個tag標籤對應一個自訂tag標籤類 -->
<description>MyTag</description>
<name>when</name>
<tag-class>cn.example.when</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>test</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
引用規則:
<%@ taglib uri="http://www.cnweb.cn" prefix="cnweb"%>

 定義錯誤處理頁面:

<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/errors/error.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/errors/error1.jsp</location>
</error-page>

自訂標籤執行流程:

SimpleTagSupport

/* Jsp引擎遇到簡單類,執行個體化該類;
* 調用setJspContext,把頁面pageContext傳遞給標籤處理類;
* 調用setParent把父標傳遞進去,如果沒有,傳遞null
* 調用setJspBody方法,把封裝了標籤體JspFragment傳遞給標籤處理器類
* 執行頁面中的自訂標籤,doTag()方法;-->執行完成,銷毀對象
*/

JspFragment jf = this.getJspBody();
jf.invoke(this.getJspContext().getOut());//如果不顯示則不進行處理

--------------------------------------------------------------------

public class tagShowOrNot extends TagSupport {
public int doStartTag() throws JspException {
return Tag.EVAL_BODY_INCLUDE;//顯示body
//return Tag.SKIP_BODY;//隱藏body
//Tag.EVAL_PAGE;//顯示page
//Tag.SKIP_PAGE;//隱藏page
}} 

TagSupport
/*編寫一個實現TagSupport的類;
*在tld檔案中對標籤處理器類進行描述(tld檔案的位置:WEB-INF下)
*在jsp頁面中匯入和使用標籤
*
*jsp執行過程中遇到自訂標籤時,先執行個體化該類;
*然後執行方法:setPageContext()-->setParent()-->doStartTag()
*如果有標籤體,一般會執列標籤體;doEndTag()-->整個標籤執行完後一般會執行:release()
*
*控制整個jsp頁面是否執行;
*控制jsp頁面某一部分內容是否執行;
*控制jsp頁面內容重複執行;
*修改jsp頁面內容輸出;
*/

//該方法在執列標籤體後,執行doEndTag()方法之前執行,直到該方法返回IterationTag.SKIP_BODY;
public int doAfterBody() throws JspException {
time--;
System.out.println("重複" + time);
if (time > 0) {
return IterationTag.EVAL_BODY_AGAIN;
} else
return IterationTag.SKIP_BODY;
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.