JSP jspInit and jspDestroy

JSP JSPInit and JSPDestroy methods

  • JSP has two callback methods that you can define within a declaration scripting element.
  • The JSP container will call them at two different points during the life of a JSP page.
    The following table describes when the container calls these methods:
    Signature Description
    public void jspInit(void) The method is called during the initialization of the JSP page, and then before the first request is processed by side. The method can be used to obtain any global resources that could be used in request processing logic. The method is optional for a JSP page and in most JSP pages not necessary.
    public void jspDestory(void) The methode is called by the container just before destroying the JSP page. This method can be used to release the resources that it acquired in jspInit(). Most JSP pages have no need to declare this method
  • Every JSP is actually a Java class. A JSP Java class implements the javax.servlet.Servlet interface. In other words, a JSP is always a servlet.
  • Many of the JSP servlet resources are ready for use when jspInit() is executed. As an example, you can bind attributes with object of any kind to the servlet context using the method getServletContext().

Example of using JSPInit_and_JSPDestroy.

In the example we use Netbeans IDE and Glassfish Server.

You can download this example here (needed tools can be found in the right menu on this page).

If you like to participate in the review of this example you must first create a Web project in Netbeans (the project name is JSPInit_and_JSPDestroy).

In this example, we will add two files, header.jsp and footer.jsp.

  • It is customary to place all include files, which are used several times in the WEB-INF folder. Some would also like the include files should have the extension .jspf, but this is not a requirement.
    Here is the file we want to include at the top of all pages:
    <h2>Java Server Page</h2>
    <hr>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is Header.jsp and folder should be WEB-INF).

    Here is the file we want to include at the bottom of all pages:
    <hr>
    Page generated on <%= (new java.util.Date()).toString() %>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is Footer.jsp and folder should be WEB-INF).

Then we need a JSP file to demonstrate how we use the JSPInit_and_JSPDestroy methods.

  • Here is the main JSP file:
    <%@ page import="java.io.File" %>
    <!DOCTYPE html >
    <html>
      <head>
        <title>Java FAQ Welcome Page</title>
      </head>
      <body>
        <div style="max-width:340px; text-align: center; ">
          <%@ include file="/WEB-INF/header.jsp" %>
    
          <h3>Welcome to a brief introduction to JSP</h3>
    
          <%!
            File[] listOfFiles = null;
            public void jspInit() {
              String path = getServletContext().getRealPath("/books");
              File folder = new File(path);
              listOfFiles = folder.listFiles();
            }
    
            public String GetTopic(String s) {
              String str = s.replace('_', ' ');
              return str.substring(0, str.indexOf('.'));
            }
          %>
          Click a link below  to the given topic.
          <%
    
            for (File file : listOfFiles) {
              if (file.isFile()) {
          %>
          <p style="width: 150px; background: #e0e0e0; 
              text-align: center; margin: 6px auto 8px auto;" >
            <a style="text-decoration: none;"  
              href='books/<%= file.getName()%> ' 
              target="show" onclick="document.getElementById('showId').height=400"> 
              <%= GetTopic(file.getName())%></a></p>
              <%
                  }
                }
              %>
          <p style="width: 150px;  text-align: center; 
              margin: 6px auto 8px auto;" >
            <a style="text-decoration: none;"  
             href='#'  onclick="document.getElementById('showId').height=0; "> 
              Clear output</a></p>
    
          <iframe id="showId" name="show" 
             src="" width="600" height="0" frameborder="0"></iframe> 
           <%@ include file="/WEB-INF/footer.jsp" %>
        </div>
       
      </body>
    </html>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is index).

How does this work?

  • We have created two JSP files, Header.jsp and Footer,jsp, which we have included in the JSP document, index.jsp.
  • In a declaration scripting elements (<%!) in the index.jsp file we have created a List of books (pdf files) and a method for use in other scripting elements.
  • Typical use of a scriptlet Scripting Element is implementing the programming of the data flow. It is also normal to use established definitions in the declaration scripting elements.
  • With a for loop and expression Scripting Element we write out data a list of possible books to choose.

Creating Deployment descriptor.

  • To run this JSP you have to deploy it to a web-server or a Application server. To deploy means to install the JSP with some instruction to a such server.
  • The instructions are mainly defined to be deployment descriptors. The standard part of the deployment descriptor should be in an XML-file with the name web.xml.

    You may need to create a Deployment descriptor file, web.xml in Netbeans.

  • The contents of the web.xml file should look like this:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="3.1" 
             xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
     http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
        <servlet>
            <servlet-name>welcome</servlet-name>
            <jsp-file>/index.jsp</jsp-file>
        </servlet>
        <servlet-mapping>
            <servlet-name>welcome</servlet-name>
            <url-pattern>/JSPTopics</url-pattern>
        </servlet-mapping>
        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>
        <welcome-file-list>
            <welcome-file>JSPTopics</welcome-file>
        </welcome-file-list>
    </web-app>
  • This file starts with the normal xml tag for a XML file and the root tag for the deployment descriptor is web-app. Every ting inside the last tag is to tell the server about our application, which in this case is a JSP file.
  • With a servlet tag we give the JSP file a servlet name, which is used in the servlet-mapping tag to specify a url for the JSP file.
  • In this way we can have many urls for the same JSP file.
  • If no session-timeout (the server ends the service of the application after this time) is given a standard timeout for the server is used as timeout for the application.
  • The welcome-file tag specifies the startup for our application, which in this case and our application is the welcome file with url JSPCars. Reorganize the welcome-file-list to what is shown above.

Creating Web-server Deployment descriptor.

  • The context-root (in example /JSPInit_and_JSPDestroy) for the application will in most cases be specified by a server vendor deployment descriptor.

    For those who participate in the review: create a Glassfish deployment descriptor in Netbeans.

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, 
    Inc.//DTD GlassFish Application Server 3.0 Servlet 3.0//EN" 
    "http://www.sun.com/software/appserver/dtds/sun-web-app_3_0-0.dtd">
    <sun-web-app error-url="">
      <context-root>/JSPInit_and_JSPDestroy</context-root>
      <class-loader delegate="true"/>
      <jsp-config>
        <property name="keepgenerated" value="true">
          <description>
            Keep a copy of the generated servlet class' java code.
          </description>
        </property>
      </jsp-config>
    </sun-web-app>

Run the application.

  • For those who participate in the review: right click the Web-project and select Run.
  • This results in that the application will be deployed to the server and started.
  • The browser will display:
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.