5.5. Initializing and Preloading Servlets and JSP Pages

This section discusses methods for controlling the startup behavior of servlets and JSP pages. In particular, it explains how you can assign initialization parameters and how you can change the point in the server life cycle at which servlets and JSP pages are loaded.

Assigning Servlet Initialization Parameters

You provide servlets with initialization parameters by means of the init-param element, which has param-name and param-value subelements. For instance, in the following example, if the InitServlet servlet is accessed by means of its registered name (InitTest), it could call getServletConfig().getInitParameter("param1") from its init method to get "Value 1" and getServletConfig().getInitParameter("param2") to get "2".

<servlet> 
  <servlet-name>InitTest</servlet-name> 
  <servlet-class>myPackage.InitServlet</servlet-class> 
  <init-param>
							<param-name>param1</param-name>
							<param-value>Value 1</param-value>
							</init-param>
							<init-param>
							<param-name>param2</param-name>
							<param-value>2</param-value>
							</init-param> 
</servlet> 

There are a few common gotchas that are worth keeping in mind when dealing with initialization parameters:

  • Return values. The return value of getInitParameter is always a String. So, for instance, in the previous example you might use Integer.parseInt on param2 to obtain an int.

  • Initialization in JSP. JSP pages use jspInit, not init. JSP pages also require use of the jsp-file element in place of servletclass, as described in Section 5.3 (Assigning Names and Custom URLs). Initializing JSP pages is discussed in the next subsection.

  • Default URLs. Initialization parameters are only available when servlets are accessed by means of their registered names or through custom URL patterns associated with their registered names. So, in this example, the param1 and param2 init parameters would be available when you used the URL http://host/webAppPrefix/servlet/InitTest, but not when you used the URL http://host/webAppPrefix/servlet/myPackage.InitServlet.

Core Warning

Initialization parameters are not available in servlets that are accessed by their default URL.


For example, Listing 5.7 shows a simple servlet called InitServlet that uses the init method to set the firstName and emailAddress fields. Listing 5.8 shows the web.xml file that assigns the name InitTest to the servlet. Figures 5-12 and 5-13 show the results when the servlet is accessed with the registered name (correct) and the original name (incorrect), respectively.

Figure 5-12. The InitServlet when correctly accessed with its registered name.


Figure 5-13. The InitServlet when incorrectly accessed with the default URL.


Listing 5.7. InitServlet.java
package moreservlets; 

import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 

/** Simple servlet used to illustrate servlet 
 *  initialization parameters. 
 */ 

public class InitServlet extends HttpServlet {
  private String firstName, emailAddress; 

  public void init() {
							ServletConfig config = getServletConfig();
							firstName = config.getInitParameter("firstName");
							emailAddress = config.getInitParameter("emailAddress");
							} 

  public void doGet(HttpServletRequest request, 
                    HttpServletResponse response) 
      throws ServletException, IOException {
    response.setContentType("text/html"); 
    PrintWriter out = response.getWriter(); 
    String uri = request.getRequestURI(); 
    out.println(ServletUtilities.headWithTitle("Init Servlet") + 
                "<BODY BGCOLOR="#FDF5E6">
" + 
                "<H2>Init Parameters:</H2>
" + 
                "<UL>
" + 
                "<LI>First name: " + firstName + "
" + 
                "<LI>Email address: " + emailAddress + "
" + 
                "</UL>
" + 
                "</BODY></HTML>"); 
  } 
} 

Listing 5.8. web.xml (Excerpt illustrating initialization parameters)
<?xml version="1.0" encoding="ISO-8859-1"?> 
<!DOCTYPE web-app PUBLIC 
    "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
    "http://java.sun.com/dtd/web-app_2_3.dtd"> 

<web-app> 
  <!-- ... --> 
  <servlet> 
    <servlet-name>InitTest</servlet-name> 
    <servlet-class>moreservlets.InitServlet</servlet-class> 
    <init-param>
							<param-name>firstName</param-name>
							<param-value>Larry</param-value>
							</init-param>
							<init-param>
							<param-name>emailAddress</param-name>
							<param-value>[email protected]</param-value>
							</init-param> 
  </servlet> 
  <!-- ... --> 
</web-app> 

Assigning JSP Initialization Parameters

Providing initialization parameters to JSP pages differs in three ways from providing them to servlets.

  1. You use jsp-file instead of servlet-class. So, the servlet element of the WEB-INF/web.xml file would look something like this:

    <servlet> 
      <servlet-name>PageName</servlet-name> 
      <jsp-file>/RealPage.jsp</jsp-file> 
      <init-param> 
        <param-name>...</param-name> 
        <param-value>...</param-value> 
      </init-param> 
      ... 
    </servlet> 
  2. You almost always assign an explicit URL pattern. With servlets, it is moderately common to use the default URL that starts with http://host/webAppPrefix/servlet/; you just have to remember to use the registered name instead of the original name. This is technically legal with JSP pages also. For example, with the example just shown in item 1, you could use a URL of http://host/webAppPrefix/servlet/PageName to access the version of RealPage.jsp that has access to initialization parameters. But, many users dislike URLs that appear to refer to regular servlets when used for JSP pages. Furthermore, if the JSP page is in a directory for which the server provides a directory listing (e.g., a directory with neither an index.html nor an index.jsp file), the user might get a link to the JSP page, click on it, and thus accidentally invoke the uninitialized page. So, a good strategy is to use url-pattern (Section 5.3) to associate the original URL of the JSP page with the registered servlet name. That way, clients can use the normal name for the JSP page but still invoke the customized version. For example, given the servlet definition from item 1, you might use the following servlet-mapping definition:

    <servlet-mapping> 
      <servlet-name>PageName</servlet-name> 
      <url-pattern>/RealPage.jsp</url-pattern> 
    </servlet-mapping> 
  3. The JSP page uses jspInit, not init. The servlet that is automatically built from a JSP page may already be using the init method. Consequently, it is illegal to use a JSP declaration to provide an init method. You must name the method jspInit instead.

To illustrate the process of initializing JSP pages, Listing 5.9 shows a JSP page called InitPage.jsp that contains a jspInit method and is placed at the top level of the deployDemo Web page hierarchy. Normally, a URL of http://localhost/deployDemo/InitPage.jsp would invoke a version of the page that has no access to initialization parameters and would thus show null for the firstName and emailAddress variables. However, the web.xml file (Listing 5.10) assigns a registered name and then associates that registered name with the URL pattern /InitPage.jsp. As Figure 5-14 shows, the result is that the normal URL for the JSP page now invokes the version of the page that has access to the initialization parameters.

Figure 5-14. Mapping a JSP page’s original URL to the registered servlet name prevents users from accidentally accessing the uninitialized version.


Listing 5.9. InitPage.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<HTML> 
<HEAD><TITLE>JSP Init Test</TITLE></HEAD> 

<BODY BGCOLOR="#FDF5E6"> 

<H2>Init Parameters:</H2> 
<UL> 
  <LI>First name: <%= firstName %> 
  <LI>Email address: <%= emailAddress %> 
</UL> 

</BODY></HTML> 

<%!
							private String firstName, emailAddress;
							public void jspInit() {
							ServletConfig config = getServletConfig();
							firstName = config.getInitParameter("firstName");
							emailAddress = config.getInitParameter("emailAddress");
							}
							%>
						

Listing 5.10. web.xml (Excerpt showing init params for JSP pages)
<?xml version="1.0" encoding="ISO-8859-1"?> 
<!DOCTYPE web-app PUBLIC 
    "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
    "http://java.sun.com/dtd/web-app_2_3.dtd"> 

<web-app> 
  <!-- ... --> 
  <servlet> 
    <servlet-name>InitPage</servlet-name> 
    <jsp-file>/InitPage.jsp</jsp-file> 
    <init-param> 
      <param-name>firstName</param-name> 
      <param-value>Bill</param-value> 
    </init-param> 
    <init-param> 
      <param-name>emailAddress</param-name> 
      <param-value>[email protected]</param-value> 
    </init-param> 
  </servlet> 
  <!-- ... --> 
  <servlet-mapping> 
    <servlet-name>InitPage</servlet-name> 
    <url-pattern>/InitPage.jsp</url-pattern> 
  </servlet-mapping> 
  <!-- ... --> 
</web-app> 

Supplying Application-Wide Initialization Parameters

Normally, you assign initialization parameters to individual servlets or JSP pages. The designated servlet or JSP page reads the parameters by means of the getInitParameter method of ServletConfig . However, in some situations you want to supply system-wide initialization parameters that can be read by any servlet or JSP page by means of the getInitParameter method of ServletContext .

You use the context-param element to declare these system-wide initialization values. The context-param element should contain param-name, param-value, and, optionally, description subelements, as below.

<context-param> 
  <param-name>support-email</param-name> 
  <param-value>[email protected]</param-value> 
</context-param> 

Recall that, to ensure portability, the elements within web.xml must be declared in the proper order. Complete details are given in Section 5.2 (The Order of Elements within the Deployment Descriptor). Here, however, just note that the context-param element must appear after any documentation-related elements (icon, display-name, and description —see Section 5.11) and before any filter (Section 5.6), filter-mapping (Section 5.6), listener (Section 5.14), or servlet (Section 5.3) elements.

Loading Servlets When the Server Starts

Suppose that a servlet or JSP page has an init (servlet) or jspInit (JSP) method that takes a long time to execute. For example, suppose that the init or jspInit method looks up constants from a database or ResourceBundle. In such a case, the default behavior of loading the servlet at the time of the first client request results in a significant delay for that first client. So, you can use the load-on-startup subelement of servlet to stipulate that the server load the servlet when the server first starts. Here is an example.

<servlet> 
  <servlet-name>...</servlet-name> 
  <servlet-class>...</servlet-class> <!-- Or jsp-file --> 
  <load-on-startup /> 
</servlet> 

Rather than using an empty load-on-startup element, you can supply an integer for the element body. The idea is that the server should load lower-numbered servlets or JSP pages before higher-numbered ones. For example, the following servlet entries (placed within the web-app element in the web.xml file that goes in the WEB-INF directory of your Web application) would instruct the server to first load and initialize SearchServlet, then load and initialize the servlet resulting from the index.jsp file that is in the Web app’s results directory.

<servlet> 
  <servlet-name>Search</servlet-name> 
  <servlet-class>myPackage.SearchServlet</servlet-class> 
  <load-on-startup>1</load-on-startup> 
</servlet> 
<servlet> 
  <servlet-name>Results</servlet-name> 
  <jsp-file>/results/index.jsp</jsp-file> 
  <load-on-startup>2</load-on-startup> 
</servlet> 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.217.220