-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCartServlet.java
More file actions
140 lines (111 loc) · 4.85 KB
/
CartServlet.java
File metadata and controls
140 lines (111 loc) · 4.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package org.example.servlets;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.model.Cart;
import org.example.model.Product;
import java.io.IOException;
import java.util.List;
@WebServlet("/cart")
public class CartServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
// Получаем или создаем корзину
Cart cart = (Cart) session.getAttribute("cart");
if (cart == null) {
cart = new Cart();
session.setAttribute("cart", cart);
}
// Передаем корзину в request scope
request.setAttribute("cart", cart);
// Перенаправляем на JSP страницу
request.getRequestDispatcher("/cart.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Cart cart = (Cart) session.getAttribute("cart");
if (cart == null) {
cart = new Cart();
session.setAttribute("cart", cart);
}
try {
// Получаем параметры
String productIdStr = request.getParameter("productId");
String quantityStr = request.getParameter("quantity");
// Проверяем, что параметры не пустые
if (productIdStr == null || quantityStr == null) {
response.sendError(400, "Все поля обязательны для заполнения");
return;
}
// Преобразуем в числа
int productId = Integer.parseInt(productIdStr);
int quantity = Integer.parseInt(quantityStr);
// Базовая проверка значений
if (productId <= 0 || quantity <= 0) {
response.sendError(400, "ID и количество должны быть положительными числами");
return;
}
// Получаем продукт
Product product = getProductById(productId);
if (product == null) {
response.sendError(404, "Товар не найден");
return;
}
// Добавляем в корзину
cart.addProduct(product, quantity);
response.sendRedirect("cart");
} catch (NumberFormatException e) {
response.sendError(400, "Неверный формат числа");
} catch (Exception e) {
response.sendError(500, "Внутренняя ошибка сервера");
}
}
@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Cart cart = (Cart) session.getAttribute("cart");
if (cart == null) {
response.setStatus(404);
return;
}
try {
// Получаем параметр
String productIdStr = request.getParameter("productId");
if (productIdStr == null) {
response.sendError(400, "Отсутствует ID товара");
return;
}
// Преобразуем в число
int productId = Integer.parseInt(productIdStr);
if (productId <= 0) {
response.sendError(400, "Неверный ID товара");
return;
}
// Удаляем продукт
cart.removeProduct(productId);
response.setStatus(200);
response.sendRedirect("cart");
} catch (NumberFormatException e) {
response.sendError(400, "Неверный формат ID товара");
}
}
private Product getProductById(int id){
ServletContext context = getServletContext();
List<Product> products = (List<Product>) context.getAttribute("products");
if (products == null) {
return null;
}
for (Product product : products) {
if (product.getId() == id) {
return product;
}
}
return null;
}
}