I recently made changes to a simple shopping cart code that originally added products from a drop-down list of games on an html page. I decided to modify the HTML by removing the drop down list and instead adding an 'add to cart' button for each game. However, I am facing difficulties in editing the cart to add the games whenever any 'add to cart' button is clicked. It's worth noting that my server-side code is utilizing jetty-9 servlets.
I would greatly appreciate some guidance and assistance!
Below is the original cart code that functioned with the drop-down list:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Cart extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException {
String s, goods[] = {"Fifa 15", "Battlefield 5", "GTA 6"};
double price []={10,20,30};
double cost;
PrintWriter out = res.getWriter();
res.setContentType("text/html");
HttpSession session = req.getSession(true);
if ( session == null ) return;
for (int i = 0; i < goods.length; i++)
if ( session.getAttribute(goods[i]) == null )
session.setAttribute(goods[i], new Integer(0));
if ( (s = req.getParameter("buy")) != null ) {
int n = ((Integer)session.getAttribute(s)).intValue();
session.setAttribute(s, new Integer(n + 1));
}
out.println("<html><body><h2>Shopping Cart</h2><ul>");
for (int i = 0; i < goods.length; i++) {
int n = ((Integer)session.getAttribute(goods[i])).intValue();
if ( n > 0 ){
out.println("<li><b>" + goods[i] + "</b> : " + n +":"+ price[i] +"</li>");
cost=n*price[i];
out.println(cost);}
}
out.println("</ul></body></html>");
}
}
Additionally, here is the updated HTML page displaying the games:
<html>
Games
<head>
</head>
<body>
<form action="http://localhost:8080/apps/Cart"method="post" >
Fifa 15 </br>
<img src="images/fifa-15.jpg" width = 200 height = 300 alt="image" /></br>
<input type="submit" value="add to cart" ></br>
Battlefield 4</br>
<img src="images/battlefield-4.jpg" width = 200 height = 300 alt="image" /></br>
<input type="submit" value="add to cart" name ="battle"></br>
GTA 5</br>
<img src="images/gta-5.jpg" width = 200 height = 300 alt="image" /></br>
<input type="submit" value="add to cart" name = "gta">
</form>
</body>
</html>