Issue
I recently started learning java ee and i want to make a small shop application. In the code below i added some articles in list and i can display them on my jsp.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ArrayList<Artical> articals = Artical.getArticals();
request.setAttribute("articals", articals);
RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
}
Here is where i display articals and where i create a button:
<body>
<h1>Welcome ${user.name}</h1>
<c:forEach var="artical" items="${articals}">
<ul>
<li>${artical.name}
<form action="addtocart" method="POST">
<button type="submit" name="button">Add to cart</button></form></li>
<li>${artical.price}</li>
</ul>
</c:forEach>
</body>
I want when i click "Add to cart" button, to add that item to cart(in my case just to display them). So how my "addtocart" servlet should look like? Thanks
Solution
You can add hidden field inside your <form></form>
so that on click of your button form will take your name
and price
values of items to servlet where you can add these in your List
.i.e:
<c:forEach var="artical" items="${articals}">
<ul>
<li>${artical.name}
<form action="addtocart" method="POST">
<!--add below inputs-->
<input type="hidden" name="names" value="${artical.name}"/>
<input type="hidden" name="price" value="${artical.price}"/>
<button type="submit" name="button">Add to cart</button></form></li>
<li>${artical.price}</li>
</ul>
</c:forEach>
Then in your servlets doPost()
method get these values using request.getParameter("..")
i.e:
String names= request.getParameter("names");
String price= request.getParameter("price");
//add in list and then add that list in sessions
Answered By - Swati