jspInit() and jspDestroy( )

If you know a bit about servlets, you know that a servlet has two methods the container calls when the servlet is loaded and shut down, respectively. These methods are called init( ) and destroy( ), and they allow the servlet to initialize instance variables when it’s loaded and clean up when it’s shut down. As you already know, a JSP page is turned into a servlet, so it has the same capability. However, with JSP, the methods are called jspInit( ) and jspDestroy( ) instead.

Again, I recommend that you don’t declare any instance variables for your JSP pages. If you follow this advice, there’s also no reason to declare the jspInit( ) and jspDestroy( ) methods. But I know you’re curious, so here’s an example of how they can be used.

Expanding on Example 16-3, the jspInit( ) method can set an instance variable to a java.util.Date( ) object, which represents the date and time when the page was initialized. This variable can then be used in the page to show when the counter was started:

<%@ page language="java" contentType="text/html" %>
<%@ page import="java.util.Date" %>
<%! 
                  int globalCounter = 0; 
                  java.util.Date startDate;
  
                  public void jspInit(  ) {
                  startDate = new java.util.Date(  );
                  }
  
                  public void jspDestroy(  ) {
                  ServletContext context = getServletConfig().getServletContext(  );
                  context.log("test.jsp was visited " + globalCounter +
      " times between " + startDate + " and " + (new Date(  )));
                  }
                  %> <html> <head> <title>A page with a counter</title> </head> <body ...

Get JavaServer Pages, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.