java.util.ArrayList无法强制转换为bean.Book

时间:2018-04-14 18:13:06

标签: java jsp

我想在带有arrayList的JSP页面中使用bean。 这是servlet代码:

 CultureInfo cul = CultureInfo.CreateSpecificCulture("es-US");
    //Parent shows es
    var parent = cul.Parent;
    ResourceManager   res_man = new ResourceManager("Resources.Resource",typeof(Resources.Resource).Assembly);
    var str = res_man.GetString("Hello", cul);

我初始化了我的arrayList,我重定向到名为“book.jsp”的JSP页面。这个JSP页面包含这段代码:

public class ResServlet extends HttpServlet{
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    String isbn = request.getParameter("isbn");
    String title = request.getParameter("title");
    String author = request.getParameter("author");
    String publisher = request.getParameter("publisher");
    String year = request.getParameter("year");
    ArrayList<Book> book = JDBC.getBooks(Integer.valueOf(isbn), title, author, publisher, Integer.valueOf(year));
    request.setAttribute("book", book);
    System.out.println("Class ResServlet :\t ISBN : " + isbn + "| title : " + title + " | author : " + author + " | publisher " + publisher + " | year : " + year );

    RequestDispatcher dispatcher = request.getRequestDispatcher("book.jsp");
    dispatcher.forward(request, response);

    }
}

当我运行我的应用程序时,我从book.jsp获得了堆栈跟踪:

<jsp:useBean id="book" class="bean.Book" scope="request"/>
<c:forEach items="${book}" var="b">
        <tr>
            <td><c:out value="${b.title}"/></td>
        </tr>
</c:forEach>

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

<jsp:useBean id="book" class="bean.Book" scope="request"/>告诉JSP,在请求范围内,您传递的bean.Book实例名称为book。 servlet编译器实际上将创建Java代码,将生成的对象强制转换为声明的类。

但是,您传递的java.util.ArrayList无法分配给bean.Book

将您的图书(或者图书)定义为<jsp:useBean id="book" class="java.util.Collection" scope="request"/> ArrayList的最常见形式是Collection

<jsp:useBean id="books" class="java.util.Collection" scope="request"/>
<c:forEach items="${books}" var="book">
    <tr>
        <td><c:out value="${book.title}"/></td>
    </tr>
</c:forEach>