12.07.2015 Views

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 7 ■ SESSION BEANS AND THE TIMER SERVICEStateful BeansStateless beans provide business methods to their clients but don’t maintain a conversational state <strong>with</strong>them. Stateful session beans, on the other hand, preserve conversational state. They are useful for tasksthat have to be done in several steps, each of which relies on the state maintained in a previous step.Let’s take the example of a shopping cart in an e-commerce web site. A customer logs on (his sessionstarts), chooses a first book, adds it to his shopping cart, chooses a second book, and adds it to his cart.At the end, the customer checks out the books, pays for them, and logs out (the session ends). Theshopping cart keeps the state of how many books the customer has chosen throughout the interaction(which can take some time, specifically the time of the client’s session).Book book = new Book();book.setTitle("The Hitchhiker's Guide to the Galaxy");book.setPrice(12.5F);book.setDescription("Science fiction comedy series created by Douglas Adams.");book.setIsbn("1-84023-742-2");book.setNbOfPage(354);book.setIllustrations(false);statefulComponent.addBookToShoppingCart(book);book.setTitle("The Robots of Dawn");book.setPrice(18.25F);book.setDescription("Isaac Asimov's Robot Series");book.setIsbn("0-553-29949-2");book.setNbOfPage(276);book.setIllustrations(false);statefulComponent.addBookToShoppingCart(book);statefulComponent.checkOutShoppingCart();The preceding code shows exactly how a stateful session bean works. Two books are created andadded to a shopping cart of a stateful component. At the end, the checkOutShoppingCart() method relieson the maintained state and can check out the two books.When a client invokes a stateful session bean in the server, the EJB container needs to provide thesame instance for each subsequent method invocation. Stateful beans cannot be reused by other clients.Figure 7-3 shows the one-to-one correlation between a bean instance and a client. As far as thedeveloper is concerned, no extra code is needed, as this one-to-one correlation is managedautomatically by the EJB container.Figure 7-3. Clients accessing stateful beans205

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!