Enterprise Java Beans manage business logic. In this module, we will explore Stateless session beans, Stateful beans, and JNDI lookup boundaries.
7.1. Stateless Session Beans vs. Stateful Session Beans
Definition: Stateless beans do not maintain client state across method calls, while Stateful beans maintain client state unique to a specific client.
Core Working Principles:
- @Stateless: Shared instance pool. Highly performant and memory efficient.
- @Stateful: Dedicated instance per client. The container manages it using passivation (writing to disk) and activation (restoring to memory).
// JNDI stateful cart lookup in servlet
HttpSession session = request.getSession(true);
ShoppingCart cart = (ShoppingCart) session.getAttribute("cartEJB");
if (cart == null) {
InitialContext ctx = new InitialContext();
cart = (ShoppingCart) ctx.lookup("java:global/App/ShoppingCartBean");
session.setAttribute("cartEJB", cart);
}
5-Marks Exam Scoring Points
- Stateless beans are pooled; Stateful beans are dedicated to single clients.
- Stateful beans must not be injected directly in servlet singletons using @EJB.
- Look up stateful beans via JNDI and store them in the user's HTTP session context.