Commit a8285ec0 by Patryk Czarnik

Basket - podejście z listenerem sesji

parent e9c2002b
package sklep.basket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
@Configuration
public class BasketConfiguration {
// Adnotacja Configuration powoduje, że:
// - Spring tworzy obiekt tej klasy (BasketConfiguration)
// - dla każdej meody oznaczonej @Bean uruchamia tę metodę, a jej wynik rejestruje jako bean
// - gdy typ wynikowy "znaczy dla Springa coś specjalnego", to Spring weźmie to pod uwagę,
// właśnie w ten sposób często podaje się Springowi elementy konfiguracji
@Bean
HttpSessionListener createListener() {
return new HttpSessionListener() {
@Override
public void sessionCreated(HttpSessionEvent se) {
HttpSession sesja = se.getSession();
// sesja.setMaxInactiveInterval(30); // pół minuty i sesja wygasa
// System.out.println("sessionCreated " + sesja.getId());
Basket basket = new Basket();
sesja.setAttribute("basket", basket);
}
};
}
}
...@@ -128,12 +128,8 @@ public class ProductController { ...@@ -128,12 +128,8 @@ public class ProductController {
HttpSession sesja) { HttpSession sesja) {
Optional<Product> product = productRepository.findById(productId); Optional<Product> product = productRepository.findById(productId);
if(product.isPresent()) { if(product.isPresent()) {
// w tej wersji stosujemy leniwą inicjalizację // w tej wersji zakładamy, że listener przygotował pusty koszyk
Basket basket = (Basket) sesja.getAttribute("basket"); Basket basket = (Basket) sesja.getAttribute("basket");
if(basket == null) {
basket = new Basket();
sesja.setAttribute("basket", basket);
}
basket.addProduct(product.get()); basket.addProduct(product.get());
} else { } else {
System.err.println("Nieznany produkt dodawany do koszyka: " + productId); System.err.println("Nieznany produkt dodawany do koszyka: " + productId);
......
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