2013-02-14 78 views
2

我想製作一個自定義標籤。在這個標籤中,我將傳遞一個Object作爲屬性,並且它應該返回一個數組列表。我已經嘗試過了,我正在得到一個異常。傳遞Object作爲JSTL標籤的屬性

org.apache.jasper.JasperException: java.lang.ClassCastException: java.lang.String cannot be cast to com.showtable.helper.ParentNode 

我覺得我的參數發送爲字符串的類,有其無法將對象轉換爲給定類型。我如何解決它,並傳遞對象本身並在類中進行類型轉換(因爲String本身是一個類,我認爲它可能,但我不知道如何去做) 我的代碼如下。 頁面內

內頁

<%@taglib prefix="test" uri="/WEB-INF/tlds/ShowTableCustomTag.tld"%> 
<% 
//the 'theMainObject' is of type ParentNode 
request.setAttribute("mainobject", theMainObject); 
%> 
<test:getorder objectpara="mainobject"></test:getorder> 

內ShowTableCustomTag.tld

<?xml version="1.0" encoding="UTF-8"?> 
<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"> 
    <tlib-version>1.0</tlib-version> 
    <short-name>showtablecustomtag</short-name> 
    <uri>/WEB-INF/tlds/ShowTableCustomTag</uri> 
<tag> 
    <name>getorder</name> 
    <tagclass>cc.showtable.customtag.ParentNodeOrder</tagclass> 
    <info>tag to return order as arraylist</info> 
    <attribute> 
     <name>objectpara</name> 
     <required>true</required> 
    </attribute> 
</tag> 
</taglib> 

裏面ParentNodeOrder類

package cc.showtable.customtag; 
import java.io.IOException; 
import javax.servlet.jsp.JspException; 
import javax.servlet.jsp.JspWriter; 
import javax.servlet.jsp.tagext.TagSupport; 
import com.showtable.helper.ParentNode; 
public class ParentNodeOrder extends TagSupport{ 

    private Object objectpara; 

    @Override 
    public int doStartTag() throws JspException { 

     try { 
      //Get the writer object for output. 
      JspWriter out = pageContext.getOut(); 
      ParentNode parent=(ParentNode)objectpara; 
      out.println(parent.getOrder()); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return SKIP_BODY; 
    } 
    public Object getObjectpara() { 
     return objectpara; 
    } 
    public void setObjectpara(Object objectpara) { 
     this.objectpara = objectpara; 
    } 

} 

回答

2

由於您在.tld文件中的<attribute>標記中缺少<type>標記,因此您遇到此例外情況。
<type>標記是可選的,並且沒有<type>標記的屬性假定爲String數據類型。
另外,您需要設置rtexprvalue = truertexprvalue代表運行時表達式值。您需要將其值設置爲true,以便可以在運行時動態計算屬性的值。
所以你attribute聲明應該是這樣的你.tld文件:

<attribute> 
    <name>objectpara</name> 
    <required>true</required> 
    <type>com.showtable.helper.ParentNode</type> 
    <rtexprvalue>true</rtexprvalue> 
</attribute> 

希望這有助於!

+0

感謝您的回答。我已經包含了類型,但是我得到了同樣的異常:( org.apache.jasper.JasperException:java.lang.ClassCastException:java.lang.String不能轉換爲com.showtable.helper.ParentNode – arjuncc 2013-02-15 10:18:24

+0

那麼我想你還需要設置'rtexprvalue = true'! – 2013-02-15 12:09:47

+0

@arjuncc!我已經更新了我的答案! – 2013-02-15 12:10:58