|
Home TOC Index |
|
Search
Feedback |
Initializing and Finalizing a JSP Page
You can customize the initialization process to allow the JSP page to read persistent configuration data, initialize resources, and perform any other one-time activities by overriding the
jspInitmethod of theJspPageinterface. You release resources using thejspDestroymethod. The methods are defined using JSP declarations, discussed in Declarations.The bookstore example page
initdestroy.jspdefines thejspInitmethod to retrieve or create an enterprise beandatabase.BookDBEJBthat accesses the bookstore database;initdestroy.jspstores a reference to the bean inbookDBEJB. The enterprise bean is created using the techniques described in .private BookDBEJB bookDBEJB; public void jspInit() { bookDBEJB = (BookDB)getServletContext(). getAttribute("bookDBEJB"); if (bookDBEJB == null) { try { InitialContext ic = new InitialContext(); Object objRef = ic.lookup( "java:comp/env/ejb/BookDBEJB"); BookDBEJBHome home = (BookDBEJBHome)PortableRemoteObject. narrow(objRef, database.BookDBEJBHome.class); bookDBEJB = home.create(); getServletContext().setAttribute("bookDBEJB", bookDBEJB); } catch (RemoteException ex) { System.out.println( "Couldn't create database bean." + ex.getMessage()); } catch (CreateException ex) { System.out.println( "Couldn't create database bean." + ex.getMessage()); } catch (NamingException ex) { System.out.println( "Unable to lookup home: " + "java:comp/env/ejb/BookDBEJB."+ ex.getMessage()); } } }When the JSP page is removed from service, the
jspDestroymethod releases theBookDBEJBvariable:public void jspDestroy() { bookDBEJB = null; }Since the enterprise bean is shared between all the JSP pages, it should be initialized when the application is started, instead of in each JSP page. Java Servlet technology provides application life cycle events and listener classes for this purpose. As an exercise, you can move the code that manages the creation of the enterprise bean to a context listener class. See Handling Servlet Life-Cycle Events for the context listener that initializes the Java Servlet version of the bookstore application.
|
Home TOC Index |
|
Search
Feedback |