JSP自定義標籤擴展----支持EL,訪問Spring容器

1、使JSP自定義標籤支持EL表達式(${}) java

我寫了自定義標籤a:rim,想讓他的title屬性支持${},但是出現了異常. web

<%  
    String str = "這是EL表達式從 request中取出來的文字!";  
    request.setAttribute("str",str);  
%>  
<a:rim title="${tut}">

要作下面兩件事就能夠達到目的了: spring

1  在tld文件以下配置: apache

<tag>  
      <icon>      
      </icon>  
      <name>rim</name>  
      <tag-class>com.xui.overall.RimTag</tag-class>  
      <body-content>JSP</body-content>  
          <attribute>  
         <name>title</name>  
         <required>false</required>  
           <rtexprvalue>true</rtexprvalue>  
      </attribute>  
   </tag>

 其中關鍵的是 <rtexprvalue>true</rtexprvalue> ,使title屬性能夠接受EL表達式. ui

2  對接收到的EL表達式處理 this

 title屬性的 set get 方法 以下寫 lua

private Object    title    = "";  
public void setTitle(final Object title) throws JspException  
    {  
        // 對EL表達式的支持  
        this.title = ExpressionEvaluatorManager.evaluate("title", title.toString(), Object.class, this, pageContext);  
    }  
  
    public Object getTitle()  
    {  
        return title;  
    }

 這裏處理${}的是org.apache.taglibs.standard.lang.support下,有個叫 ExpressionEvaluatorManager類, code

 ExpressionEvaluatorManager.evaluate有五個參數。第一個title屬性的名字,本例用"title"就行。第二個要求字符串,一般簡單調用輸入對象的toString方法。第三個是類,一般用Object.class。第四個用this便可,第五個是pageContext變量。 xml

注意:當你的tag屬性支持el表達式時,你必須把它聲明爲Object對象:本例中是 private Object    title    = "標題"; 對象

這樣工做就作完了,自定義標籤就能夠處理 ${}了.

 

 

2、若是在JSP自定義標籤中,需要拿到spring IOC容器管理的bean能夠:

你的JSP自定義標籤類能夠從org.springframework.web.servlet.tags.RequestContextAwareTag繼承,使用 getRequestContext().getWebApplicationContext()能夠獲得spring的context

相關文章
相關標籤/搜索