Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Session Beans Contents 1. Session bean concepts 2. Stateless session beans 3. Stateful session beans 2 1. Session Bean Concepts Session bean interfaces and classes Defining metadata Packaging and deployment Operation at run time 3 Session Bean Interfaces and Classes To define a session bean: • • Define a remote and/or local interface Define the bean class Client calls business methods on bean, via the EJB object EJB object EJB bean Proxy for the EJB bean object Business functionality or business data You define remote and/or local interface Your EJB tool generates the source code for the EJB object Delegates You define the bean class You write the methods specified in the remote and/or local interface 4 Defining Metadata You can provide metadata to accompany session beans • There are 3 ways to provide metadata • • • E.g. transactional requirements, security, etc. Implicit defaults Annotations Deployment descriptors Are annotations or deployment descriptors better? • Discuss 5 Packaging and Deployment Enterprise application (EAR file) EJB module (EJB-JAR file) Remote interface Remote interface Local interface Local i/f Local interface Bean Bean class Remote i/f Bean class Web module (WAR file) Remote interface Remote interface Local interface Servlets/JSPs Local interface Client code Client code Application client Client code 6 Operation at Run Time At start-up, the EJB server can create a pool of beans When a client accesses a bean, it just gets an EJB object When a client calls a method, a bean is acquired from pool When a bean is unneeded, the bean is returned to pool EJB objects Bean pool Client 1 Client 2 Client 3 7 2. Stateless Session Beans Overview of stateless session beans Defining the remote / local interfaces Defining exceptions Ensuring consistency Defining the bean class Stateless session bean life cycle Using the bean Using the bean in a Web application 8 Overview of Stateless Session Beans Stateless session beans do not retain client-specific state between method calls • Lightweight and scalable If a client invokes a series of methods on a stateless session bean… • • The methods might be executed on different bean instances This doesn't matter at all, because stateless session beans do not contain any client-specific state 9 Defining the Remote / Local Interfaces The remote and/or local interface specifies the 'business methods' for your bean • Annotate an interface with @Remote or @Local Example remote and local interfaces: package demos.sessionbeans.ejb; import javax.ejb.Remote; TempConverterBeanRemote.java in the DemosSessionBeansEJB project @Remote public interface TempConverterBeanRemote { public double fToC(double fahr); public double cToF(double celsius); } package demos.sessionbeans.ejb; import javax.ejb.Local; TempConverterBeanLocal.java in the DemosSessionBeansEJB project @Local public interface TempConverterBeanLocal { public double fToC(double fahr); public double cToF(double celsius); } 10 Ensuring Consistency If you want to expose the same business interface remotely and locally… • The remote and local interfaces must be the same To ensure the remote and local interfaces are the same… • Define a base interface that the remote and local interfaces extend public interface TempConverter { public double fToC(double fahr); public double cToF(double celsius); } @Remote public interface TempConverterBeanRemote extends TempConverter {} @Local public interface TempConverterBeanLocal extends TempConverter {} 11 Defining the Bean Class The next step is to write the bean class, which implements the business methods for your bean In EJB 3.x, the implementation class is a POJO • Just annotate the class with @Stateless or @Stateful, and implement the remote and/or local interface package demos.sessionbeans.ejb; import javax.ejb.Stateless; TempConverterBean.java in the DemosSessionBeansEJB project @Stateless public class TempConverterBean implements TempConverterBeanRemote, TempConverterBeanLocal { public TempConverterBean() {} public double fToC(double fahr) { return (fahr - 32) * 5 / 9; } public double cToF(double celsius) { return (celsius * 9 / 5) + 32; } } 12 Stateless Session Bean Life Cycle (1 of 2) The life cycle of a stateless session bean is very simple: Does Not Exist Class.newInstance() @PreDestroy method injections @PostConstruct method Ready Pool business method 13 Stateless Session Bean Life Cycle (2 of 2) A bean class can define methods to be invoked during bean start-up and shut-down • • Annotate start-up method with @PostConstruct Annotate shut-down method with @PreDestroy @Stateless TempConverterBean.java public class TempConverterBean implements TempConverterBeanRemote, TempConverterBeanLocal { … @PostConstruct public void myPostConstructMethod() { System.out.println("Bean created at: " + new Date()); } @PreDestroy public void myPreDestroyMethod() { System.out.println("Bean destroyed at: " + new Date()); } } 14 Using the Bean (1 of 3) Generally you can inject a bean reference where needed • • Declare a variable of the remote interface type Annotate the variable with @EJB import javax.ejb.EJB; import demos.sessionbeans.ejb.TempConverterBeanRemote; … @EJB private TempConverterBeanRemote tempConverterBean; You can explicitly tell the EJB container how to resolve the dependency injection: @EJB(mappedName="MyTempConverterBean") private TempConverterBeanRemote tempConverterBean; You can inject a reference to a bean on a different server: @EJB(mappedName="corbaname:iiop:localhost:3700#MyTempConverterBean") private TempConverterBeanRemote tempConverterBean; 15 Using the Bean (2 of 3) You can also get a bean via a manual global JNDI lookup... • To look-up a bean by its remote interface type: InitialContext context = new InitialContext(); bean = (TempConverterBeanRemote)context.lookup( "demos.sessionbeans.ejb.TempConverterBeanRemote"); • To look-up a bean by its mappedName: InitialContext context = new InitialContext(); bean = (TempConverterRemote)context.lookup("MyTempConverterBean"); • To look-up a bean on a specific server: Hashtable env = new Hashtable(); env.put("org.omg.CORBA.ORBInitialHost", "localhost"); env.put("org.omg.CORBA.ORBInitialPort", "3700"); InitialContext context = new InitialContext(env); bean = (TempConverterRemote)context.lookup("MyTempConverterBean"); 16 Using the Bean (3 of 3) After you have acquired access to a bean, you can use it as follows: Main.java public class Main { in the DemosSessionBeansClient project … private static void testStatelessBean() { TempConverterBeanRemote tc = … ; … try { System.out.println("212F = " + tc.fToC(212) + "C"); System.out.println("100C = " + tc.cToF(100) + "F"); } catch (InvalidTempException ex) {…} } } 17 Using the Bean in a Web App (1 of 2) A Web app can access an EJB via its remote interface public class MyServlet extends HttpServlet { @EJB private TempConverterBeanRemote bean; Using injection protected void doGet(…) … { … out.println("212F = " + bean.fToC(212) + "C"); out.println("100C = " + bean.cToF(100) + "F"); Using global JNDI lookup public class MyServlet extends HttpServlet { protected void doGet(…) … { InitialContext context = new InitialContext(); TempConverterBeanRemote bean = (TempConverterRemote)context.lookup("MyTempConverterBean"); … out.println("212F = " + bean.fToC(212) + "C"); out.println("100C = " + bean.cToF(100) + "F"); 18 Using the Bean in a Web App (2 of 2) If a bean has a local interface, you can access it from Web apps in the same EAR application file • Same as on previous slide, but using local interface(!) But... you can't lookup the bean's local interface in JNDI • • Most Java EE servers don't add bean local interfaces to JNDI! Solution: Manually add the bean's local interface to your local JNDI namespace Lookup the bean's local interface in your local JNDI namespace @EJB(name="ejb/TempConverter", beanInterface=demos.sessionbeans.ejb.TempConverterBeanLocal.class) public class MyServlet extends HttpServlet { protected void doGet(…) … { InitialContext context = new InitialContext(); TempConverterBeanLocal bean = (TempConverterBeanLocal) context.lookup("java:comp/env/ejb/TempConverter"); … 19 3. Stateful Session Beans Overview of stateful session beans Defining the remote /local interface Defining the bean class Stateful session bean life cycle Using the bean in a client application Using the bean in a Web application 20 Overview of Stateful Session Beans Stateful session beans hold conversations with a particular client, which span multiple method calls • • Stateful session beans must therefore retain state between method calls The state is specific to a particular client 21 Defining the Remote / Local Interface The remote / local interfaces specify the 'business methods' for your bean • The rules for defining remote / local interfaces are the same as for stateless session beans For example: package demos.sessionbeans.ejb; import javax.ejb.Remote; import java.util.List; ShoppingCartBeanRemote.java in the DemosSessionBeansEJB project @Remote public interface ShoppingCartBeanRemote { public void addItem(String productName); public void removeItem(String productName); public List<String> getItems(); } 22 Defining the Bean Class (1 of 2) The bean class must be annotated with @Stateful • Indicates it's a stateful session bean The bean class must implement the business methods that are specified in the remote / local interfaces • • The bean class (and almost always does) have instance variables The instance variables are preserved in a stateful session bean 23 Defining the Bean Class (2 of 2) package demos.sessionbeans.ejb; ShoppingCartBean.java import javax.ejb.Stateful; import java.util.*; @Stateful public class ShoppingCartBean implements ShoppingCartBeanRemote { private List<String> items = new ArrayList<String>(); public void addItem(String productName) { items.add(productName); } public void removeItem(String productName) { items.remove(productName); } public List<String> getItems() { return items; } } 24 Stateful Session Bean Life Cycle (1 of 2) The life cycle of a stateful session bean is as follows: Does Not Exist Class.newInstance() @PreDestroy method injections @PostConstruct @PrePassivate() Ready @PostActivate() Passive business method 25 Stateful Session Bean Life Cycle (2 of 2) The following example shows how to define life cycle methods for a stateful session bean ShoppingCartBean.java @Stateful public class ShoppingCartBean implements ShoppingCartBeanRemote, ShoppingCartBeanLocal { … @PostConstruct public void myPostConstructMethod() {…} @PreDestroy public void myPreDestroyMethod() {…} @PrePassivate public void myPrePassivateMethod() {…} @PostActivate public void myPostActivateMethod() {…} } 26 Using the Bean in a Client App package demos.sessionbeans.appclient; import demos.sessionbeans.ejb.ShoppingCartBeanRemote; import javax.ejb.EJB; … public static void testStatefulBean() { try { InitialContext context = new InitialContext(); ShoppingCartBeanRemote cart = (ShoppingCartBeanRemote) context.lookup("demos.sessionbeans.ejb.ShoppingCartBeanRemote"); cart.addItem("Sky Sports"); cart.addItem("OLED 4KHD TV"); cart.addItem("Carving skis"); cart.removeItem("Sky Sports"); System.out.println("Items in your shopping cart:"); for (String item : cart.getItems()) { System.out.printf("Item: %s\n", item); } } catch (Exception ex) { System.out.println("Exception: " + ex.getMessage()); } } Main.java in the DemosSessionBeansClient project 27 Using the Bean in a Web App (1 of 4) You can access stateful session beans in a Web app • Do not use injection for stateful session beans • • • However, you must be very careful... This would mean each servlet instance gets its own session bean This probably isn't what you want! You want each client to get its own session bean Do use manual JNDI lookup • • • • Look up the bean using JNDI Insert the bean into HTTP session scope Next time round, get the bean from HTTP session scope (not JNDI) This way, each client has its own session bean 28 Using the Bean in a Web App (2 of 4) Initial Web page, to enable user to enter an item to be added to shopping cart: <h2>Manage your Shopping Cart</h2> ManageShoppingCart.html <form action="ShoppingCartServlet" method="get"> <input type="text" name="txtItem" /> <input type="submit" value="Add to cart" /> </form> ShoppingCartServlet 29 Using the Bean in a Web App (3 of 4) Servlet (controller) ShoppingCartServlet.java @WebServlet(name="ShoppingCartServlet", urlPatterns={"/ShoppingCartServlet"}) @EJB(name="ejb/Cart", beanInterface=demos.sessionbeans.ejb.ShoppingCartBeanLocal.class) public class ShoppingCartServlet extends HttpServlet { protected void doGet(…) { // Get existing ShoppingCart bean from HTTP session, or lookup new one. HttpSession sess = request.getSession(); ShoppingCartBeanLocal bean = (ShoppingCartBeanLocal)sess.getAttribute("Cart"); if (bean == null) { InitialContext context = new InitialContext(); bean = (ShoppingCartBeanLocal)context.lookup("java:comp/env/ejb/Cart"); sess.setAttribute("Cart", bean); } // Invoke business method on bean, to add item to shopping cart. bean.addItem(request.getParameter("txtItem")); // Redisplay HTML form and shopping cart JSP. … } } 30 Using the Bean in a Web App (4 of 4) JSP (view) DisplayShoppingCart.jsp <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%-- Does session scope have a "Cart" attribute? --%> <c:if test="${not empty sessionScope.Cart}"> <%-- Get items in ShoppingCart bean, and assign to local variable --%> <c:set var="itemsInCart" value="${sessionScope.Cart.items}" /> <%-- Iterate through the items --%> Items in shopping cart: <br/> <ul> <c:forEach var="item" items="${itemsInCart}"> <li>${item}</li> </c:forEach> </ul> </c:if> 31 Summary Introduction to EJBs • EJBs are transactional middle-tier components Session beans provide functionality in the "middle tier" • • Stateless session beans are conversation-less Stateful session beans are conversational (per-client) 32 Any Questions? 33