Issue
I'm practising Java ee and I made a two input fields and button in jsp. When clicked on button "add" I want to add those two fields in a list and just show them on my jsp page. For now it's showing me only one result each time I click on button. What am I doing wrong?
This is my jsp:
<body>
<form action="addtocart" method="GET">
Title: <input type="text" name="title"> <br>
Price: <input type="text" name="price"> <br>
<button type="subtmit">Add</button>
</form>
<c:forEach var="bookList" items="${book}">
<ul>
<li>${bookList.name}</li>
<li>${bookList.price}</li>
</ul>
</c:forEach>
</body>
And this is my servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
String title = request.getParameter("title");
double price = Double.parseDouble(request.getParameter("price"));
ArrayList<Book> list = new ArrayList<>();
list.add(new Book(title,price));
session.setAttribute("book", list);
RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
}
Solution
Problem
You are creating a new ArrayList<Book>
on every call of doGet
and setting the same into the session. Thus, on every call of doGet
the list is getting reset.
Solution
Get the existing list from the session and add a book to it. Create a new list only when it is not present in the session.
@WebServlet("/addtocart")
public class BooklistServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
String title = request.getParameter("title");
double price = Double.parseDouble(request.getParameter("price"));
ArrayList<Book> list = (ArrayList<Book>) session.getAttribute("book");
if (list == null) {
list = new ArrayList<Book>();
}
list.add(new Book(title, price));
session.setAttribute("book", list);
RequestDispatcher view = request.getRequestDispatcher("home.jsp");
view.forward(request, response);
}
}
Additionally, I recommend you display the list only when it is not empty as shown below:
<body>
<form action="addtocart" method="GET">
Title: <input type="text" name="title"> <br> Price: <input
type="text" name="price"> <br>
<button type="submit">Add</button>
</form>
<c:forEach var="bookList" items="${book}">
<c:if test="${not empty book}">
<ul>
<li>${bookList.title}</li>
<li>${bookList.price}</li>
</ul>
</c:if>
</c:forEach>
</body>
As you can see, I've added the check <c:if test="${not empty book}">
as a condition for the visibility of the list.
Answered By - Arvind Kumar Avinash