это мой AddToCart.jsp:
Код: Выделить всё
Item Added to Cart
Item Added to Cart
You have successfully added [b][/b] to your cart.
[url=Cart.jsp]
View Cart
[/url]
[url=home.jsp]
Continue Shopping
[/url]
Код: Выделить всё
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/addToCart")
public class AddToCartServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Retrieve the item details from the request
String title = request.getParameter("title"); // Get item title from request
int id = Integer.parseInt(request.getParameter("id")); // Get item ID from request
// Create a new item
Item newItem = new Item(id, title);
// Get the user's session
HttpSession session = request.getSession();
// Retrieve the cart from the session
List cart = (List) session.getAttribute("cart");
if (cart == null) {
cart = new ArrayList(); // If cart doesn't exist, initialize it
}
// Add the new item to the cart
cart.add(newItem);
session.setAttribute("cart", cart); // Update the session with the new cart
// Redirect to the confirmation page with the item title
response.sendRedirect("cartConfirmation.jsp?title=" + URLEncoder.encode(title, "UTF-8"));
}
// Item class to represent an item in the cart
private static class Item {
private int id;
private String title;
public Item(int id, String title) {
this.id = id;
this.title = title;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
}
}
Код: Выделить всё
Your Cart
Your Cart
Your cart is currently empty.
[url=home.jsp]
Continue Shopping
[/url]
Item
Author
Price
Actions
$
Remove
Total: $
[url=checkout.jsp]
Proceed to Checkout
[/url]
Подробнее здесь: https://stackoverflow.com/questions/792 ... -from-cart