将Object作为JSTL标记属性传递

时间:2013-02-14 12:44:45

标签: java exception object attributes jstl

我正在尝试制作自定义标签。在这个标签中,我将传递一个Object作为属性,它应该返回一个数组列表。我试过了,我得到一个例外的例外。

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

我认为我的参数是作为String发送给类的,并且它无法将对象强制转换为给定的类型。我怎样才能解决它并传递Object本身并在类中进行类型转换(因为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;
    }

}

1 个答案:

答案 0 :(得分:2)

您遇到此异常,因为您遗漏了<type>文件中<attribute>标记内的.tld标记。
<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>

希望这有帮助!