在JSP中解密一组对象

时间:2014-03-21 15:10:36

标签: java jsp servlets

我有一个从servlet传递到jsp的对象数组

我有一个名为object的班级,位于com.example

class object {

String param1;

//getters and setters

}

我的servlet代码:

object[] sampleObject = new object[5];

// code to populate object 

RequestDispatcher dispatch = request.getRequestDispatcher("/inc/example.jsp"); 
request.setAttribute("object", sampleObject);
dispatch.forward(request, response);

我的example.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
    <%@ page import="java.util.*" %>
 <%@ page import="com.example.object" %>
    <jsp:useBean id="object" scope="request" class="java.util.Arrays" />

     <%
     int l = object.length;
    %>

此操作因错误The value for the useBean class attribute java.lang.Arrays is invalid

而失败

当我尝试

<jsp:useBean id="object" scope="request" class="com.example.object" />

我得到的错误是

The type of the expression must be an array type but it resolved to object

它仍然失败。我应该如何配置我的jsp来使用它。

我的类应该在jsp:useBean中为对象定义。当我使用com.example.object

时,我选择java.util.Arrays作为无效而对我大喊大叫

2 个答案:

答案 0 :(得分:0)

试试这个:

<jsp:useBean id="object" scope="request" class="java.lang.Object" />

至少你可以获得数组,然后使用显式转换来获取特定属性。但最好使用EL标签迭代数组。

答案 1 :(得分:0)

我认为这就是你要做的事情:

创建一个长度为5的对象,而不是一个包含5个对象的数组。

所以在你的班级添加一个长度属性:

class object {

    String param1;
    int length;

    //getters and setters
    public void setLength(int length) {
        this.length = length;
    }
    public int getLength() {
        return this.length;
    }

}

现在,您可以创建新对象并设置其长度。

 object sampleObject = new object();
 sampleObject.setLength(5);

最后,你可以从你的jsp页面调用它。

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<%@ page import="java.util.*" %>
<%@ page import="com.example.object" %>
<jsp:useBean id="object" scope="request" class="com.example.object" />

<% int l = object.getLength(); %>
相关问题