2013-03-31 33 views
0

這裏是我的Servlet,其中將文本框值添加到ArrayList。我也在使用JavaBeans。在迭代JSTL中的ArrayList時獲取空白頁面

protected void doPost(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException { 

     String companyName = request.getParameter("txtCompany"); 
     double price = Double.parseDouble(request.getParameter("txtPrice")); 
     HttpSession session = request.getSession(); 
     // Invoice r = new Invoice(); 

     ArrayList<Invoice> list = (ArrayList<Invoice>) session 
       .getAttribute("EInvoice.list"); 

     if (list == null) { 
      list = new ArrayList<Invoice>(); 
     } 
     list.add(new Invoice(companyName, price)); 

     session.setAttribute("EInvoice.list", list); 

     String url = "/Show.jsp"; 

     RequestDispatcher rd = getServletContext().getRequestDispatcher(url); 
     rd.forward(request, response); 

    } 

這裏是Show.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
     pageEncoding="ISO-8859-1"%> 
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 


    <html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
    <title>Show</title> 
    </head> 
    <body> 
     <c:forEach var="list" items="${EInvoice.list}"> 
      <h1>${list.companyName} ${list.price}</h1> 
     </c:forEach> 
    </body> 
    </html> 

我希望它顯示輸入的文本框的值,但所有我得到的是一個空白頁。任何想法爲什麼?當我正在學習JSTL時,請諒解任何愚蠢的代碼錯誤。

回答

4

expression language (EL)中,期間.是一個特殊的操作符,它將屬性從bean中分離出來。它不應該用於屬性名稱中,否則您必須使用括號符號顯式指定範圍映射。您的具體問題是由於它正在搜索具有確切名稱「EInvoice」的屬性,然後嘗試調用getList()方法。但是,在EL範圍中不存在這樣的屬性,因此沒有什麼可以迭代。

至於說,你可以改用支具符號範圍地圖上指它:

<c:forEach var="list" items="${sessionScope['EInvoice.list']}"> 

不過,我建議只重命名的屬性名稱。例如: -

session.setAttribute("invoices", invoices); 

和等價:

<c:forEach var="invoice" items="${invoices}"> 
    <h1>${invoice.companyName} ${invoice.price}</h1> 
</c:forEach> 

請注意,我也馬上做出變量名稱更自我記錄。當查看變量名「list」時,人們不知道它包含哪些項目。另外,命名循環中的列表「list」的每個迭代項目都沒有意義。