6.7. Calling the Session Bean from the Controller ServletWe're now going to introduce the InventoryFacadeBean to the JAW Motors application by calling it from the Controller Servlet. We'll modify the Controller Servlet so it uses the InventoryFacadeBean rather than the DAO to list the cars on the web page. For now, all other actions in the Controller Servlet still use the DAO. Example 6-4 shows the changes. Example 6-4. ControllerServlet.javapackage com.jbossatwork; ... import com.jbossatwork.ejb.*; ... import javax.ejb.*; ... public class ControllerServlet extends HttpServlet { ... protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... InventoryFacadeLocalHome inventoryHome; inventoryHome = (InventoryFacadeLocalHome) ServiceLocator.getEjbLocalHome(InventoryFacadeLocalHome.COMP_NAME); InventoryFacadeLocal inventory = null; try { inventory = inventoryHome.create( ); } catch (CreateException ce) { throw new RuntimeException(ce.getMessage( )); } // perform action if (VIEW_CAR_LIST_ACTION.equals(actionName)) { request.setAttribute("carList", inventory.listAvailableCars( )); destinationPage = "/carList.jsp"; } ... } } The InventoryFacadeBean is a JNDI-based resource, so we've encapsulated the JNDI lookup with the ServiceLocatorwe'll show the look up code in detail in the next section. The ServiceLocator.getEjbLocalHome( ) call does a JNDI lookup on the EJB's Local Home, and creates a Local Home Interface. The viewCarList action now calls the InventoryFacade's listAllAvailableCars( ) method to find all available (unsold) cars in the inventory. Now that we've shown how to invoke the InventoryFacadeBean, let's take a closer look at the ServiceLocator that wraps the JNDI lookup. 6.7.1. Factoring Out the JNDI CallsWe've used the ServiceLocator tHRoughout this book to wrap JNDI lookup calls Example 6-5 is the new EJB-related method. Example 6-5. ServiceLocator.javapackage com.jbossatwork.util; ... import javax.ejb.*; ... import javax.naming.*; ... public class ServiceLocator { ... public static EJBLocalHome getEjbLocalHome(String localHomeJndiName) throws ServiceLocatorException { EJBLocalHome localHome = null; try { Context ctx = new InitialContext( ); localHome = (EJBLocalHome) ctx.lookup(localHomeJndiName); } catch (ClassCastException cce) { throw new ServiceLocatorException(cce); } catch (NamingException ne) { throw new ServiceLocatorException(ne); } return localHome; } ... } The getEjbLocalHome( ) method encapsulates a JNDI look up for an EJB Local Home object. This method takes the following steps:
We've written all the necessary code to call an EJB, and now we need to add EJB-based JNDI references to our web deployment descriptors. |