Commit bc493fad by Patryk Czarnik

Listener sesji i inicjalizacja koszyka w inny sposób

parent 6a2446ae
......@@ -25,11 +25,8 @@ public class AddToBasket extends HttpServlet {
Product product = productDAO.findById(id);
HttpSession session = request.getSession();
Basket basket = (Basket) session.getAttribute("basket");
if(basket == null) {
basket = new Basket();
session.setAttribute("basket", basket);
}
Basket basket = (Basket)session.getAttribute("basket");
// Zakładamy, że obiekt basket istnieje, gdyż został utworzony przez listenera
basket.addProduct(product);
}
} catch(Exception e) {
......
package sklep.basket;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener
public class BasketInitialization implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent se) {
// To się wykona, gdy jakaś sesja jest tworzona.
HttpSession sesja = se.getSession();
sesja.setMaxInactiveInterval(30); // czas wygaśnięcia sesji w sekundach
System.out.println("Powstała sesja " + sesja.getId());
sesja.setAttribute("basket", new Basket());
}
public void sessionDestroyed(HttpSessionEvent se) {
// To się wykona, gdy jakaś sesja jest usuwana (kończy się).
HttpSession sesja = se.getSession();
System.out.println("Koniec sesji " + sesja.getId());
}
}
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