The J2EETM Tutorial
Home
TOC
Index
PREV TOP NEXT 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 jspInit method of the JspPage interface. You release resources using the jspDestroy method. The methods are defined using JSP declarations, discussed in Declarations.

The bookstore example page initdestroy.jsp defines the jspInit method to retrieve or create an enterprise bean database.BookDBEJB that accesses the bookstore database; initdestroy.jsp stores a reference to the bean in bookDBEJB. 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 jspDestroy method releases the BookDBEJB variable:

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
PREV TOP NEXT Search
Feedback