Reputation: 13
Here is my Servlet in which adding the textbox values to an ArrayList. I am also using JavaBeans.
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);
}
Here is the 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>
I expect it to show the entered textbox values, but all I am getting is a blank page. Any idea why? Pardon any silly code mistakes as I am learning JSTL.
Upvotes: 0
Views: 853
Reputation: 1108742
In expression language (EL), the period .
is a special operator which separates the property from the bean. It should not be used in an attribute name, or you must otherwise explicitly specify the scope map using the brace notation. Your concrete problem is caused because it's searching for an attribute with exact name "EInvoice" on which it would then try to call the getList()
method. However, no such attribute exists in the EL scope and hence there's nothing to iterate over.
As said, you can instead use the brace notation on the scope map to refer it:
<c:forEach var="list" items="${sessionScope['EInvoice.list']}">
However, I recommend to just rename the attribute name. E.g.:
session.setAttribute("invoices", invoices);
and equivalently:
<c:forEach var="invoice" items="${invoices}">
<h1>${invoice.companyName} ${invoice.price}</h1>
</c:forEach>
Note that I also immediately made the variable names more self documenting. When looking at variable name "list" one would have no clue what items exactly it contains. Also, naming each iterated item of a list "list" in the loop makes no utter sense.
Upvotes: 4