即使已发送属性,JSP代码仍显示为空

时间:2018-07-01 16:47:28

标签: java jsp servlets requestdispatcher

我没主意了。我打印了从Servlet发送来的ArrayList书籍,并且一直显示为null。当我在Servlet中打印该数组时,它将显示正确的数据集。也许您可以帮助我: 这是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);

}

这是我的JSP代码:

<%@ 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>

我认为在分发时或JSP本身中一定有错误。 我100%确保我提供的.jsp文件名正确。 有什么想法吗?

2 个答案:

答案 0 :(得分:1)

根据此代码

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

您正在获得列表而不是对象。 最好使用for循环在体内打印列表对象,例如

<%
for (int i = 0; i < theBooks.size(); i++)
      {
         System.out.println(theBooks.get(i).toString());
      }
%>

答案 1 :(得分:1)

您的项目是否使用mvc概念构建?如果是这样,那么我假设您有一个豆书课,也许这是其中之一:

public int getBookID() {
    return bookID;
}

然后按照bean中的方法在jsp中提取“ BOOKED_LIST”:

<%@ 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>