JSP自訂標籤庫

來源:互聯網
上載者:User

標籤:自訂標籤庫   java   jstl   

今天閑來無事,於是想起自己之前一直使用的標籤,無論是jstl,struts標籤還是springmvc標籤,使用起來都覺得很方便,於是自己想嘗試定義自己的標籤。

下面把今天自己的成果給大家分享下。要自訂標籤並使用標籤,需要以下幾步:

1、定義自己的標籤解析類,一般都是繼承TagSupport類(servlet-api.jar),Override該類的doStartTag()或者doEndTag()方法;

2、定義.tld檔案;

3、在web.xml中聲明要使用的標籤(也可以不聲明);

4、在jsp中使用自訂的標籤。

下面通過一個例子來給大家詳細的講解:

1、定義自己的第一個標籤解析類:

package com.jrj.tag.example;import java.io.IOException;import javax.servlet.jsp.JspException;import javax.servlet.jsp.tagext.TagSupport;@SuppressWarnings("serial")public class FirstTag extends TagSupport{@Overridepublic int doEndTag() throws JspException {try {pageContext.getOut().write("hello world");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return EVAL_PAGE;}}


2、在web-inf下建立一個tagFile檔案夾,然後在檔案中建立一個example.tld,內容如下:

<?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE taglib  PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"  "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"><taglib><tlib-version>1.0</tlib-version><jsp-version>1.2</jsp-version><short-name>em</short-name><uri>http://com.jrj.tag/em</uri><display-name>Example</display-name>  <description>em 1.0 library</description><tag><name>out</name><tag-class>com.jrj.tag.example.FirstTag</tag-class><body-content>JSP</body-content><description>writer out the cotentes</description></tag></taglib>


3、如果你想在web.xml檔案中添加標籤的聲明,在web.xml中添加如下一段代碼:

<jsp-config>    <taglib>    <taglib-uri>/em</taglib-uri>    <taglib-location>/WEB-INF/tagFile/example.tld</taglib-location>    </taglib></jsp-config>

note:在今天講解的這些案例中,我沒有在web.xml中添加以上代碼,如果添加了那麼在後面jsp的引用標籤時會有所不同,希望大家注意!

4、在jsp中使用標籤,在使用之前需要先引用標籤:

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %><%@ taglib uri="http://com.jrj.tag/em" prefix="em" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head></head><body><em:out></em:out></body></html>

下面我給大家擴充兩個其他的例子,一個是關於條件運算式,一個是關於迭代以及標籤的嵌套:

1、關於條件運算式,按照上面給大家講解的步驟:

1)、

package com.jrj.tag.example;import javax.servlet.jsp.JspException;import javax.servlet.jsp.tagext.TagSupport;@SuppressWarnings("serial")public class IfTag extends TagSupport{private boolean condition;@Overridepublic int doStartTag() throws JspException {return condition?EVAL_BODY_INCLUDE:SKIP_BODY;}public boolean isCondition() {return condition;}public void setCondition(boolean condition) {this.condition = condition;}}


2)、在example.tld中添加如下內容:

<tag><name>if</name><tag-class>com.jrj.tag.example.IfTag</tag-class><body-content>JSP</body-content><description>If Condition</description><attribute><name>condition</name><required>true</required><rtexprvalue>true</rtexprvalue><type>boolean</type><description>condition</description></attribute></tag>


3)、jsp中使用,jsp修改完後變成如下:

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %><%@ taglib uri="http://com.jrj.tag/em" prefix="em" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head></head><body><em:out></em:out><em:if condition="${1==1}">if is validate</em:if></body></html>


2、關於迭代及標籤的嵌套

1)、標籤解析類

package com.jrj.tag.example;import java.util.Collection;import java.util.Iterator;import javax.servlet.jsp.JspException;import javax.servlet.jsp.tagext.BodyTagSupport;@SuppressWarnings("serial")public class ForEachTag extends BodyTagSupport {@SuppressWarnings("rawtypes")private Collection items;private String var;@SuppressWarnings("rawtypes")private Iterator it;@Overridepublic int doStartTag() throws JspException {if(items==null||items.size()==0)return SKIP_BODY;it = items.iterator();if(it.hasNext()){pageContext.setAttribute(var, it.next());}return EVAL_BODY_INCLUDE;}@Overridepublic int doAfterBody() throws JspException {if(it.hasNext()){pageContext.setAttribute(var, it.next());return EVAL_BODY_AGAIN;}return SKIP_BODY;}@Overridepublic int doEndTag() throws JspException {return EVAL_PAGE;}@SuppressWarnings("rawtypes")public Collection getItems() {return items;}@SuppressWarnings("rawtypes")public void setItems(Collection items) {this.items = items;}public String getVar() {return var;}public void setVar(String var) {this.var = var;}}

2)、在example.tld中添加如下內容:

<tag><name>foreach</name><tag-class>com.jrj.tag.example.ForEachTag</tag-class><body-content>JSP</body-content><description>ForEach The Collection</description><attribute><name>var</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute><attribute><name>items</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute></tag>


3)、jsp中使用,jsp內容如下:

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %><%@ taglib uri="http://com.jrj.tag/em" prefix="em" %><%@ page import="java.util.*" %><%String path = request.getContextPath();ArrayList<String> values = new ArrayList<String>();values.add("zhouming");values.add("xiaoshou");values.add("minggou");pageContext.setAttribute("values", values);%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head></head><body><em:out></em:out><em:if condition="${1==1}">if is validate</em:if><em:foreach items="${pageScope.values}" var="val"><em:out></em:out>${val}</em:foreach></body></html>


下面大家可能會對兩個方面有疑問:一是java類中每個方法的傳回值的含義,二是tld檔案中一些元素代表的意思。

1、在我們建立自訂的標籤時,在複寫父類的方法是,需要注意傳回值的含義,不同的傳回值代表不同的處理,下面是不同傳回值所代表的含義:

EVAL_BODY_INCLUDE:把Body讀入存在的輸出資料流中,doStartTag()函數可用

EVAL_PAGE:繼續處理頁面,doEndTag()函數可用

SKIP_BODY:忽略對Body的處理,doStartTag()和doAfterBody()函數可用

SKIP_PAGE:忽略對餘下頁面的處理,doEndTag()函數可用

EVAL_BODY_TAG:已經廢止,由EVAL_BODY_BUFFERED取代

EVAL_BODY_BUFFERED:申請緩衝區,

由setBodyContent()函數得到的BodyContent對象來處理tag的body,

如果類實現了BodyTag,那麼doStartTag()可用,否則非法

2、如果我們需要對body裡面的內容進行迴圈處理,我們自訂的標籤解析類需要實現BodyTag介面或者繼承BodyTagSupport類

3、在我們自訂的tld檔案中,需要注意attribute元素下的rtexprvalue(Run-time Expression value)元素的值,如果該值為true,表示該屬性的值可以通過直接指定或者

通過運算式來指定,如果該值為false,則表示該屬性的值必須直接指定。

以上就是自訂標籤的基本步驟,我今天在做的過程中借鑒了jstl的實現過程以及上網找了一些資料。我覺得這種方式效率很高,如果大家還有什麼更加高效的方法,

可以分享出來,大家一起進步!我們下期再見!


本文出自 “技術無止盡,學習需多動腦” 部落格,請務必保留此出處http://wenqiangv.blog.51cto.com/7889138/1433218

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.