Taglib原理和實現之嵌套和屬性讀取

來源:互聯網
上載者:User

1、問題:在request裡有一個 Man 對象,它有兩個屬性:name和age。現在,我們想用一個嵌套的tag,父tag取得對象,子tag取得name屬性並顯示在頁面上。例如,它的形式如下:

<diego:with object="${Man}">
<diego:output property="name"/>
</diego:with>

object 支援el運算式,表示取得 Man 對象。output的property表示從該對象取得名為name的屬性。

2、如何支援tag之間的嵌套

在子tag裡調用getParent 方法,可以得到父tag對象。用 findAncestorWithClass 方法,則可以通過遞迴找到想要找的tag。例如

<diego:with object="${people}"> <!--表示取得一個對象-->
<diego:withCollection property="men"> <!--表示取得對象裡的一個屬性,這個屬性是個 Collection,Collection裡添加了許多man,每個man有名字和年齡-->
<diego:output property="name"/> <!--取得name屬性並顯示-->
</diego:withCollection>
</diego:with>

對於最內層的outputTag來說,調用getParent,可以得到 withCollectionTag,通過如findAncestorWithClass(this,WithTag.class)的方式,可以得到withTag。得到Tag之後,就可以取得Tag的屬性,進行商務邏輯處理,然後輸出到jsp

3、如何支援類屬性尋找功能

顯然,在上面的outputTag中,我們要根據屬性的名字,尋找類中有沒有這個屬性。然後取出屬性的值並顯示。通常,這可以編寫自己的反射函數來完成。更簡單的辦法,是通過 BeanUtil 的PropertyUtils方法來完成功能。BeanUtil 是apache上的一個開源項目。

樣本如下:

import org.apache.commons.beanutils.PropertyUtils;
......
property = PropertyUtils.getProperty(currentClass, propertyName);

propertyName是待尋找屬性的名字,例如上面的"name",currentClass是待尋找的類,例如上面的People

記得把 commons-beanutils.jar添加到WEB-INF\lib目錄下

4、現在讓我們實現開篇提出的問題,編寫WithTag如下:

package diegoyun;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager;
/**
* @author chenys
*/
public class WithTag extends BodyTagSupport
{
 private Object value = null;
 private Object output = null;
 public void setOutput(Object output)
 {
  this.output = output;
 }
 public Object getValue()
 {
  return value;
 }
 public void setValue(Object value)throws JspException
 {
  this.value = ExpressionEvaluatorManager.evaluate("value", value.toString(), Object.class, this, pageContext);
 }
 public int doStartTag()
 {
  return EVAL_BODY_INCLUDE;
 }
 public int doEndTag()throws JspException
 {
  try
  {
   pageContext.getOut().print(output);
  }
  catch (IOException e)
  {
   throw new JspException(e);
  }
  return EVAL_PAGE;
 }
}

聯繫我們

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