Sunday, 18 December 2011

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 the JspPage interface. You release resources using the jspDestroy method.
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.
private BookDBEJB bookDBEJB;
public void jspInit() {
   bookDBEJB =
   if (bookDBEJB == null) {
      try {

         InitialContext ic = new InitialContext();
         Object objRef = ic.lookup(
         BookDBEJBHome home =
         bookDBEJB = home.create();

      } catch (RemoteException ex) {
            "Couldn't create database bean." + ex.getMessage());
      } catch (CreateException ex) {
            "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.

No comments:

Post a Comment