Commit 3d440089 by Patryk Czarnik

@SessionAttribute i HttpSessionListener

parent 5ba4f3c4
package sklep.basket;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class BasketConfiguration {
// Klasa typu Configuration działa tak:
// - na starcie aplikacji Spring tworzy jeden obiekt tej klasy
// - szuka metod z adnotacją @Bean i je wywołuje
// - wyniki tych metod zapamiętuje jako "beany"
// - jeśli typ wynikowy takiej metody jest specjalnym typem, który "coś dla springa znaczy",
// to może wpłynąć na działanie aplikacji
// Tak jest w tym przypadku: HttpSessionListener będzie używany do obserwacji tworzonych i usuwanych sesji.
@Bean
public HttpSessionListener createSesionListener() {
// Zwracam obiekt klasy anonimowej; obiekt zgodny z interfejsem HttpSessionListener
return new HttpSessionListener() {
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);
}
public void sessionDestroyed(HttpSessionEvent se) {
HttpSession sesja = se.getSession();
System.out.println("sessionDestroyed " + sesja.getId());
}
};
}
}
package sklep.controller;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
......@@ -91,14 +90,9 @@ public class ProductController {
@GetMapping("/{id}/add-to-basket")
public String addToBasket(
@PathVariable("id") int productId,
HttpSession sesja) {
@SessionAttribute Basket basket){
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";
......
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