0

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?

Luke_Nuke
  • 461
  • 2
  • 6
  • 23
  • The issue was in the different file. In index.html I forgot to add hidden data type which I use later to recognize if I shall just display the list, or update and displayed. If only displayed whole SQL query is omitted there is no input query, just query to get data. – Luke_Nuke Jul 18 '18 at 15:52

2 Answers2

1

According to this code

 List<Book> theBooks = (List<Book>) request.getAttribute("BOOKED_LIST");

you are getting list not object. You better use for loop to print object of list inside body like

<%
for (int i = 0; i < theBooks.size(); i++)
      {
         System.out.println(theBooks.get(i).toString());
      }
%>
Avijit Barua
  • 2,950
  • 5
  • 14
  • 35
1

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>
frianH
  • 7,295
  • 6
  • 20
  • 45