Search code examples
javajspservletsrequestdispatcher

JSP code displays null even though attribute was sent


I ran out of ideas. I printed my ArrayList books which I send from my Servlet and it is displaying null all the time. When I printed that array in Servlet it displays correct set of data. Maybe you can help me: This is Servlet:

    private void listBookedPlaces(HttpServletRequest request, HttpServletResponse response)
    throws Exception {

    // get list of booked places from db util
    List<Book> books = bookDbUtil.getBooks();

    // add booked places to the request
    request.setAttribute("BOOKED_LIST", books); // set Attribute  (-name "BOOKED_LIST", -value books);

    // send to JSP page (view)
    RequestDispatcher dispatcher = request.getRequestDispatcher("/list-book.jsp");
    dispatcher.forward(request, response);

}

and this is my JSP code:

<%@ page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.util.*, com.pbs.web.jdbc.*" %>

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>PSBS - Booked Parking Spaces Tracker</title>
</head>
<%
    // "BOOKED-LIST" is attribiute name set in ControllerServlet
    List<Book> theBooks = 
            (List<Book>) request.getAttribute("BOOKED_LIST");                      
%>
<body>
    <%= theBooks %>
</body>
</html>

I think an error must be somwhere while dispatching or in the JSP itself. I'm 100% sure that .jsp file name i provided is correct. Any ideas?


Solution

  • Is your project built using mvc concept? if so, then I assume you have a bean book class, maybe this is one of them :

    public int getBookID() {
        return bookID;
    }
    

    then extract 'BOOKED_LIST' in your jsp as per method in bean :

    <%@ page contentType="text/html" pageEncoding="UTF-8"%>
    <%@ page import="java.util.*, com.pbs.web.jdbc.*" %>
    
    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>PSBS - Booked Parking Spaces Tracker</title>
    </head>
    <%
        // "BOOKED-LIST" is attribiute name set in ControllerServlet                      
    %>
    <body>
        <c:forEach var="bookBean" items="${BOOKED_LIST}">
            <tr>
                <td>${bookBean.getBookID()}</td>
            </tr>
        </c:forEach>
    </body> 
    </html>