Commit 5ba4f3c4 by Patryk Czarnik

Basket - HttpSession

parent 474e279a
package sklep.controller;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import sklep.basket.Basket;
import sklep.model.Product;
import sklep.repository.ProductRepository;
import sklep.util.PhotoUtil;
......@@ -86,6 +88,22 @@ public class ProductController {
}
}
@GetMapping("/{id}/add-to-basket")
public String addToBasket(
@PathVariable("id") int productId,
HttpSession sesja) {
Optional<Product> product = productRepository.findById(productId);
if(product.isPresent()) {
Basket basket = (Basket) sesja.getAttribute("basket");
if(basket == null) {
basket = new Basket();
sesja.setAttribute("basket", basket);
}
basket.addProduct(product.get());
}
return "redirect:/products";
}
@GetMapping("/szukaj")
public String szukaj(Model model,
String name,
......
......@@ -9,6 +9,20 @@
</head>
<body>
<c:if test="${not empty basket and not empty basket.elements}">
<div class="basket">
<h4>Koszyk</h4>
<ul>
<c:forEach var="p" items="${basket.elements}">
<li>${p.productName}: ${p.quantity} × ${p.price} = <b>${p.value}</b></li>
</c:forEach>
</ul>
<p>Wartość koszyka: ${basket.totalValue}</p>
</div>
</c:if>
<h1>Wszystkie produkty</h1>
<c:forEach var="product" items="${products}">
......@@ -18,6 +32,7 @@
<p>Cena: <span class="product-price">${product.price}</span></p>
<p class="product-description">${product.description}</p>
<div class="action"><a href="/products/${product.productId}/edit">Edytuj</a></div>
<div class="action"><a href="/products/${product.productId}/add-to-basket">Dodaj do koszyka</a></div>
</div>
</c:forEach>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment