Commit 5750167b by Patryk Czarnik

koszyk - wersja z ServletContextem

parent 6a348825
package sklep.basket;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import sklep.model.Product;
public class Basket {
private final Map<Integer, ProductInBasket> elementy = new HashMap<>();
public synchronized void addProduct(Product product, int quantity) {
if(elementy.containsKey(product.getProductId())) {
// jeśli w słowniku jest już taki element, to tylko zwiększamy ilość
elementy.get(product.getProductId()).increaseQuantity(quantity);
} else {
// jeśli jeszcze nie ma, to tworzymy
elementy.put(product.getProductId(),
new ProductInBasket(product.getProductId(), product.getProductName(), product.getPrice(), quantity));
}
}
public synchronized void addProduct(Product product) {
// "domyślną ilością, o którą zwiększamy, jest 1"
addProduct(product, 1);
}
public synchronized Collection<ProductInBasket> getElements() {
return Collections.unmodifiableCollection(elementy.values());
}
public synchronized BigDecimal getTotalValue() {
return getElements().stream()
.map(ProductInBasket::getValue)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
@Override
public synchronized String toString() {
return "Koszyk o rozmiarze " + getElements().size()
+ " i wartości " + getTotalValue();
}
}
package sklep.basket;
import java.math.BigDecimal;
import java.util.Objects;
public class ProductInBasket {
private int productId;
private String productName;
private BigDecimal price;
private int quantity;
public ProductInBasket(int productId, String productName, BigDecimal price, int quantity) {
this.productId = productId;
this.productName = productName;
this.price = price;
this.quantity = quantity;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getProductId() {
return productId;
}
public String getProductName() {
return productName;
}
@Override
public String toString() {
return "ElementKoszyka [productId=" + productId + ", productName=" + productName + ", price=" + price
+ ", quantity=" + quantity + "]";
}
@Override
public int hashCode() {
return Objects.hash(price, productId, productName, quantity);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProductInBasket other = (ProductInBasket) obj;
return Objects.equals(price, other.price) && productId == other.productId
&& Objects.equals(productName, other.productName) && quantity == other.quantity;
}
public BigDecimal getValue() {
return price.multiply(BigDecimal.valueOf(quantity));
}
public void increaseQuantity(int change) {
quantity += change;
}
}
package sklep.web;
import java.io.IOException;
import javax.servlet.ServletContext;
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 sklep.basket.Basket;
import sklep.db.DBConnection;
import sklep.db.ProductDAO;
import sklep.model.Product;
@WebServlet("/AddToBasket")
public class AddToBasket extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
int id = Integer.parseInt(request.getParameter("productId"));
try(DBConnection db = DBConnection.open()) {
ProductDAO productDAO = db.productDAO();
Product product = productDAO.findById(id);
ServletContext servletContext = this.getServletContext();
Basket basket = (Basket) servletContext.getAttribute("basket");
if(basket == null) {
basket = new Basket();
servletContext.setAttribute("basket", basket);
}
basket.addProduct(product);
}
} catch(Exception e) {
// ignorujemy błędy
}
// Przekierowanie - każemy przeglądarce wejść pod ten adres.
response.sendRedirect("products8.jsp");
}
}
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Lista produktów 8</title>
<link rel="stylesheet" type="text/css" href="styl.css">
</head>
<body>
<h1>Lista produktów - wersja 8 JSP z koszykiem</h1>
<p>[<a href="index.html">powrót do spisu treści</a>]</p>
<%-- Za pomocą klasy ProductBean odczytamy z bazy listę produktów w postaci obiektowej. --%>
<jsp:useBean id="bean" class="sklep.beans.ProductBean"/>
<div class="koszyk">
<h4>Koszyk</h4>
<ul>
<%-- Zauważmy, że dla obiektu koszyk nie wykonujemy już useBean.
Po prostu zakładamy, że jest obecny (w sesji). Gdyby go nie było, to pętla się nie wykona. --%>
<c:forEach var="elm" items="${basket.elements}">
<li>${elm.productName} (${elm.quantity}) za <b>${elm.value}</b></li>
</c:forEach>
</ul>
<p class="total">Do zapłaty: ${basket.totalValue}</p>
</div>
<h2>Filtr cen</h2>
<form id="wyszukiwarka" method="get">
<table class="formularz">
<tr><td><label for="min_price">Cena minimalna:</label></td>
<td><input type="number" name="min_price" value="${param.min_price}"></td></tr>
<tr><td><label for="max_price">Cena maksymalna:</label></td>
<td><input type="number" name="max_price" value="${param.max_price}"></td></tr>
<tr><td><button>Szukaj</button></td></tr>
</table>
</form>
<%-- Kryteria wyszukiwania przysłane w parametrach z formularza przekazuję do bean za pomocą setterów. --%>
<jsp:setProperty name="bean" property="minPrice" param="min_price"/>
<jsp:setProperty name="bean" property="maxPrice" param="max_price"/>
<c:forEach var="product" items="${bean.filteredProducts}">
<div class="product">
<img class="photo" src="Photo?productId=${product.productId}" alt=""/>
<h3>${product.productName}</h3>
<div class="price">Cena: ${product.price}</div>
<div class="price">VAT ${product.vat * 100}%</div>
<c:if test="${not empty product.description}">
<p>${product.description}</p>
</c:if>
<div><a href="AddToBasket?productId=${product.productId}">dodaj do koszyka</a></div>
</div>
</c:forEach>
<p>[<a href="index.html">powrót do spisu treści</a>]</p>
</body>
</html>
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