Commit 1b114571 by Patryk Czarnik

@SessionAttribute i listener jako klasa anonimowa

parent 80be96ed
......@@ -3,6 +3,8 @@ 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
......@@ -12,7 +14,20 @@ public class BasketConfig {
@Bean
HttpSessionListener createListener() {
return new BasketListener();
return new HttpSessionListener() {
@Override
public void sessionCreated(HttpSessionEvent se) {
HttpSession session = se.getSession();
session.setMaxInactiveInterval(60);
session.setAttribute("basket", new Basket());
System.out.println("Początek sesji " + session.getId());
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("Koniec sesji " + se.getSession().getId());
}
};
}
}
package sklep.basket;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
public class BasketListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent se) {
HttpSession session = se.getSession();
session.setMaxInactiveInterval(30); // sesja wygasa po pół minuty - tylko na potrzeby zajęć
session.setAttribute("basket", new Basket());
System.out.println("Początek sesji " + session.getId());
}
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("Koniec sesji " + se.getSession().getId());
}
}
......@@ -13,6 +13,7 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
......@@ -106,9 +107,8 @@ public class ProductController {
@GetMapping("/{id}/add-to-basket")
public String addToBasket(
@PathVariable("id") int productId,
HttpSession session) {
@SessionAttribute Basket basket) {
Basket basket = (Basket) session.getAttribute("basket");
Optional<Product> product = productRepository.findById(productId);
if(product.isPresent()) {
basket.addProduct(product.get());
......
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