States need to be maintained between calls. In EJB3 all beans are homeless [no home interface]//ShoppingCartBean.javaimport java.io.Serializable;import java.util.HashMap;import javax.ejb.Remove;import javax.ejb.Stateful;import javax.ejb.Remote;@Stateful@Remote(ShoppingCart.class)public class ShoppingCartBean implements ShoppingCart, Serializable{ private HashMap cart = new HashMap(); public void buy(String product, int quantity) { if (cart.containsKey(product)) { int currq = cart.get(product); currq += quantity; cart.put(product, currq); } else { cart.put(product, quantity); } } public HashMap getCartContents() { return cart; } @Remove public void checkout() { System.out.println("To be implemented"); }}//ShoppingCart.java//remote interfaceimport java.util.HashMap;import javax.ejb.Remove;public interface ShoppingCart{ void buy(String product, int quantity); HashMap getCartContents(); @Remove void checkout();}//client//Client.java//client uses JNDI to look up for EJB servicesimport java.util.HashMap;import javax.naming.InitialContext;import org.jboss.tutorial.stateful.bean.ShoppingCart;public class Client{ public static void main(String[] args) throws Exception { InitialContext ctx = new InitialContext(); ShoppingCart cart = (ShoppingCart) ctx.lookup("ShoppingCartBean/remote"); System.out.println("Buying 1 memory stick"); cart.buy("Memory stick", 1); System.out.println("Buying another memory stick"); cart.buy("Memory stick", 1); System.out.println("Buying a laptop"); cart.buy("Laptop", 1); System.out.println("Print cart:"); HashMap fullCart = cart.getCartContents(); for (String product : fullCart.keySet()) { System.out.println(fullCart.get(product) + " " + product); } System.out.println("Checkout"); cart.checkout(); System.out.println("Should throw an object not found exception by invoking on cart after @Remove method"); try { cart.getCartContents(); } catch (javax.ejb.EJBNoSuchObjectException e) { System.out.println("Successfully caught no such object exception."); } }}
From: http://sitestree.com/?p=4833
Categories:Java Short Notes
Tags:
Post Data:2008-11-20 09:48:27
Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada