Reputation: 759
I want to use bean in a JSP page with an arrayList. Here is the servlet code :
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);
}
}
One I have initialized my arrayList, I make a redirection to a JSP page named "book.jsp". This JSP page contains this piece of code :
<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>
When I run my application, I have got that stacktrace from book.jsp :
java.lang.ClassCastException: java.util.ArrayList cannot be cast to bean.Book
org.apache.jsp.book_jsp._jspService(book_jsp.java:139)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:444)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
servlet.ResServlet.doGet(ResServlet.java:29)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Thanks for your help!
Upvotes: 1
Views: 1151
Reputation: 3563
<jsp:useBean id="book" class="bean.Book" scope="request"/>
tells the JSP that in the request scope you are passing a bean.Book
instance under the name of book
. The servlet compiler will actually create Java code that will cast the resulting object to the declared class.
However you are passing a java.util.ArrayList
, which is not assignable to a bean.Book
.
Define your book (or should it be books) as <jsp:useBean id="book" class="java.util.Collection" scope="request"/>
The most general form of an ArrayList
is a 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>
Upvotes: 2