Article

Java Servlets - Part 2

Page: 1 2 3 4 5 Next

Servlet Initialization Parameters

Like any potentially complex piece of software, Servlets can have configuration settings and options that can be enabled or disabled. In the world of Servlets, these settings are called initialization parameters, and are set in the web.xml file we discussed last time.

A common use of an initialization parameter is to enable debug output. For example, if a Servlet connects to a database to retrieve some information to display on the page, you might want to display the commands that are sent to the database while you are developing the Servlet so that you can be sure everything is working well behind the scenes. But when it comes time to deploy the Servlet in a production environment, you wouldn't want those debug messages to be displayed. By using an initialization parameter to set whether debug output is displayed, you can easily build a Servlet that is appropriate for use in both development and production environments. Let's take a look at how this would be done.

The HttpServlet class that all of your Servlets should extend has a getInitParameter method that retrieves the value of an initialization parameter given its name. Since all Servlets are subclasses of HttpServlet, they all inherit that method. Thus, getting the value of an init parameter is as simple as this:

String param = getInitParameter("paramName");

In the case of our parameter for enabling debug output, we could just call getInitParameter("debug") every time we needed to check, but a much more efficient solution (which saves you some typing, too) is to check once when the Servlet is first loaded and store the result as a boolean (true/false) variable.

To perform some action when a Servlet is loaded, you need to give your Servlet an init method. Here's the skeleton of a Servlet that has a boolean property variable debug that is assigned its value at load time by the init method:

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
 
public class MyDebugServlet extends HttpServlet {  
 
 boolean debug;  
 
 public void init() throws ServletException {  
   String debugParam = getInitParameter("debug");  
   if (debugParam != null &&  
       debugParam.equalsIgnoreCase("true")) {  
     debug = true;  
   } else {  
     debug = false;  
   }  
 }  
 
 // ... doGet, doPost, etc. ...  
}

As you can see, the init method must be declared to throw a ServletException. A ServletException is the type of error that the init method (and most other Servlet methods) can produce to tell the server that something went wrong, and to display an error message because the Servlet isn't working as expected. I'll demonstrate this in the final example in this article, but in this case our Servlet won't have need to produce such errors. Nevertheless, the init method must be declared as if it could.

The first thing init does in the above is to fetch the debug init parameter (getInitParameter("debug")). Like the getParameter function we saw in the previous section (for fetching request parameters), getInitParameter will return null if the parameter was not specified at all. Thus, before we use the debugParam variable, we should make sure it's not null (trying to call a method on a null variable will cause your Servlet to crash with a NullPointerException error):

if (debugParam != null &&  
   debugParam.equalsIgnoreCase("true")) {

This if statement uses the AND (&&) operator. In words, it says

if debugParam isn't null and debugParam is "true" (ignoring case)...

Since calling equalsIgnoreCase would cause a NullPointerException if debugParam were null, it's important that we check that it isn't first. Java is pretty smart, so if one condition AND (&&) another condition have to be true in an if statement, and it turns out that the first condition is false, then Java won't bother even checking the second condition. In this case, if debugParam is null then Java will skip the second condition and avoid the crash.

So if the if statement turns out to be true, then we set our debug property variable true. If not, we set debug to false. We can then use this property variable to determine whether or not to display debug output in our doGet method:

if (debug) out.println("Debug output here!");

The following variation on the RequestType2 Servlet we developed at the beginning of this article only displays the request type if the debug parameter is set to true (RequestType3.java):

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
 
public class RequestType3 extends HttpServlet {  
 
 boolean debug;  
 
 public void init() throws ServletException {  
   String debugParam = getInitParameter("debug");  
   if (debugParam != null &&  
       debugParam.equalsIgnoreCase("true")) {  
     debug = true;  
   } else {  
     debug = false;  
   }  
 }  
 
 public void doGet(HttpServletRequest req, HttpServletResponse rsp)  
               throws ServletException, IOException {  
   rsp.setContentType("text/html");  
   PrintWriter out = rsp.getWriter();  
 
   String requestType = req.getMethod();  
 
   out.println("<html>");  
   out.println("<head><title> A Web page </title></head>");  
   out.println("<body>");  
 
   if (debug) out.println("<p>This page is the result of a " +  
                          requestType + " request.</p>");  
 
   out.println("<p>Regular page content here...</p>");  
   out.println("</body></html>");  
 }  
 
 public void doPost(HttpServletRequest req, HttpServletResponse rsp)  
               throws ServletException, IOException {  
   doGet(req,rsp);  
 }  
 
}

As you can see, the above code uses the init method from our skeleton code above to set the debug property based on an init parameter, then if debug output is requested we display the request type:

   if (debug) out.println("<p>This page is the result of a " +  
                          requestType + " request.</p>");

Compile (or download RequestType3.class) and deploy this Servlet, then load it. You should only see the "Regular page content here..." paragraph (no debug output):

No debug outputNow, the question remains: how do we set initialization parameters? For this, we return to the web.xml file, which you'll find in the WEB-INF directory (e.g. C:\Program Files\Apache Group\jakarta-tomcat-3.2.3\webapps\ROOT\WEB-INF\web.xml). You'll recall in Part 1 we used this file to specify names and mappings for our Servlets. With a new tag, <init-param>, you can set initialization parameters for a Servlet. The following web.xml file, for instance, assigns our RequestType3 Servlet the name rt3 and gives it an initialization parameter called debug with a value of true. The <description> tag is actually optional, but we use it to explain what the parameter does.

<?xml version="1.0" encoding="ISO-8859-1"?>  
 
<!DOCTYPE web-app  
   PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"  
   "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">  
 
<web-app>  
 <servlet>  
   <servlet-name>  
     rt3  
   </servlet-name>  
   <servlet-class>  
     RequestType3  
   </servlet-class>  
   <init-param>  
     <param-name>  
       debug  
     </param-name>  
     <param-value>  
       true  
     </param-value>  
     <description>  
       Set to 'true' for debug output.  
     </description>  
   </init-param>  
 </servlet>  
</web-app>

Now if you load the RequestType3 Servlet using its assigned name (http://localhost:8080/servlet/rt3) you'll see the debug output:

Debug output displayed

If you liked this article, share the love:
Print-Friendly Version Suggest an Article