How to access/read the init-params defined in the web.xml from Servlet/JSP

How To Access/Read The Init-Params Defined In The web.xml From A Servlet/JSP

Date: 27/01/2004

This Document will help you understand:
• How to add init parameters to web.xml that can be accessed in a servlet/JSP
• How to access/read init parameters defined in web.xml from a servlet/JSP
• How to run the sample servlet/JSP application

Table of Contents

Introduction
Prerequisites
Software Requirements
How to Access/Read Init Parameters defined in web.xml from a Servlet/JSP
Running the Sample Servlet Applications
Useful References
FAQ

Introduction 

Servlets provide a component-based platform-independent method for building web-based applications, and are generally used to generate dynamic web content. To put it simply, a servlet receives a request from a client (the web browser, for instance), processes the request, and returns the response to the client. For example, the response can be a queried from a database that is displayed using HTML.

For more information about Servlets, refer to the Useful References section later in this document.

JavaServer Pages (JSPs) on the other hand is an extension of the Java Servlet technology. When executed, JSPs get compiled to servlets. JavaServer Pages technology separates the user interface from content generation enabling designers to change the overall page layout without altering the underlying dynamic content.

What are servlet initialization parameters?

Initialization Parameters are name/value pair that specify the initial values of the servlet/JSP variables. They can be used to customize and control the behavior of a servlet or a JSP. For example, you can define a parameter for a JNDI name of a data source or a parameter that can be initialized to count the hits of the page.

The init parameters can be defined in the application's Web Application Deployment Descriptor file - web.xml. A servlet container uses a servlet configuration object ServletConfig and, getInitParameter() method to read the init parameters from the web.xml, and passes the information to a servlet during initialization.

In case of the JSP, they can be read from jspInit() method or directly in a Java scriplet using the implicit object: ServletConfig.

Prerequisites 

To work your way through this HowTo, it is necessary to have a basic understanding of the fundamental concepts of servlets, and how to develop and deploy them to a web server.

Software Requirements

  • Oracle JDeveloper 10g or later ( JDeveloper is Oracle's Visual Java Development Tool and can be downloaded from here)
    OR
    Oracle Application Server Containers for J2EE(OC4J) 9.0.3 or later. ( Download from here )
  • JDK1.3.x or later. (Download from here )

How To access/read initialization parameters defined in web.xml from a Servlet/JSP

This section provides the steps to run and access init parameters from a Servlet/JSP.

  1. Adding Init Parameter Entries in the web.xml file
  2. Reading the Init Parameters from the web.xml file
  1. Adding Init Parameter Entries in the web.xml file

    Init parameters are added between the <init-param></init-param> tags under the <servlet></servlet> tags in the web.xml file. For example, the following web.xml entries show the init parameters for the servlet - ReadInitParametersServlet, and the JSP - ReadInitParamJSP.

    The init parameters defined for the example servlet are "emailHost" and "webMaster". The init parameters defined for the example JSP are "sys" and "master".

  2. web.xml for Servlet/JSP

    <web-app>
      <!-- Init parameters for the servlet ReadInitParams -->
    <servlet> <servlet-name>ReadInitParams</servlet-name> <servlet-class>oracle.otnsamples.servlets.ReadInitParametersServlet</servlet-class> <display-name>Read Initialization Parameters of the Servlet</display-name> <init-param> <param-name>emailHost</param-name> <param-value>151.68.167.201</param-value> </init-param> <init-param> <param-name>webMaster</param-name> <param-value>Savitha Rajeev</param-value> </init-param> </servlet>
    <!-- Init parameters for the JSP readInitParamJSP -->
    <servlet>
    <servlet-name>
    readInitParamJSP</servlet-name>
    <jsp-file>
    /web/readInitParamJSP.jsp</jsp-file>
    <init-param>
    <param-name>
    sys</param-name>
    <param-value>
    151.68.167.201</param-value>
    </init-param>
    <init-param>
    <param-name>
    master</param-name>
    <param-value>
    OTN Group IDC</param-value>
    </init-param>
    </servlet>

    <servlet-mapping>
    <servlet-name>readInitParamJSP</servlet-name>
    <url-pattern>/web/readInitParamJSP.jsp</url-pattern>
    </servlet-mapping> </web-app>


  3. Reading the Init Parameters from the web.xml file

    The ServletConfig object provides a handle to the initialization parameters defined in web.xml. ServletConfig's method: getInitParameter() is used to retrieve the init parameters. The following code snippet illustrates how to read the init parameters from the init() and the service() methods of a servlet.

public void init(ServletConfig config) throws ServletException {
   String emailHost  = config.getInitParameter("emailHost");
   String webMaster  = config.getInitParameter("webMaster");
}

or public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String host = getServletConfig().getInitParameter("emailHost");
String master = getServletConfig().getInitParameter("webMaster");
}

To retrieve all the init parameters, use Enumeration and ServletConfig's getInitParmeterNames(). For example,

public void init(ServletConfig config) throws ServletException {
   Enumeration params = config.getInitParameterNames();

   // Print the init parameter names and values to the console
   while (params.hasMoreElements()) {
       String name = (String) params.nextElement();
       System.out.println("Parameter Name: " + name +
                          " Value: " + config.getInitParameter(name));
   }
}

Reading the init parameters from the web.xml file in a JSP

The implicit object - ServletConfig can be read either in the jspInit() method or directly to retrieve the values of init parameters. Following is the code snippet to retrieve the values from readInitParamJSP.jsp

readInitParamJSP.jsp
<%@ page language="java"%>
<html>
<head><title>Read Init params from a JSP</title></head>
<body>
<%!
String emailHost = null;
String webMaster = null;
public void jspInit() {
ServletConfig config = getServletConfig();
emailHost = config.getInitParameter("emailHost");
webMaster = config.getInitParameter("webMaster");
}
%>
<table border="1">
<tr><td>email server</td><td><%=emailHost%></td></tr>
<tr><td>WebMaster</td><td><%=webMaster%></td></tr>
</table> <% // It can also be read directly from the implicit object - config %>
<%=config.getInitParameter("sys")%><br><br>
<%=config.getInitParameter("master")%>
</body>
</html>

Running the Sample Servlet Application

This section talks about how to get the servlets up and running. The application downloadable Jar file demonstrates the way the to access/read the init parameters defined in web.xml, from a servlet as well as a JSP.

Running the Servlet sample application in OC4J (EAR Deployment):

The sample application ReadInitParams.jar can be downloaded from here. The Jar file extracts all the sample application files to a folder called ReadInitParams. Go through the following steps to deploy and run the servlet/JSP in OC4J.

    1. Add servlet.jar to the CLASSPATH; this file is present under <OC4J_HOME>/j2ee/home/lib folder.
      Note: <OC4J_HOME> is the folder where the OC4J server is installed; for example, d:\oc4j
    2. From the ReadInitParams folder, compile the servlet file ReadInitParametersServlet.java.
      javac src/oracle/otnsamples/servlets/*.java -d ./WEB-INF/classes
      - This creates the ReadInitParametersServlet.class file under the WEB-INF/classes/oracle/otnsamples/servlets folder.
    3. Next, create a WAR file containing all the servlet classes, JSPs, HTML files and the web.xml file using the JAR command:
      jar -cvfM initparams.war WEB-INF/* web/*.jsp

    4. Create a EAR file containg the application.xml file and WAR file using the JAR command again.
      jar -cvfM initparams.ear initparams.war META-INF
    5. Start the OC4J server.
    6. Deploy the servlet applications using the command below:

      java -jar <OC4J_HOME>/j2ee/home/admin.jar ormi://<server>:<rmiport> admin <admin_password> -deploy -file <Sample_Name>.ear -deploymentName <earDeploymentName>

      Example:
      java -jar D:/oc4j903/j2ee/home/admin.jar ormi://incq207a.idc.oracle.com:23791 admin welcome -deploy -file initparams.ear -deploymentName initparams

      Note:
      <server> is the IP Address of the system where the OC4J instance is running.
      <rmiport> is the RMI port number of the OC4J instance; default is 23791
      <admin_password> is the password of the OC4J installation
      <Sample_Name>.ear is the EAR file created, that is, initparams.ear
      <earDeploymentName> is the deployment name for the application, that is, initparams

    7. Bind the web application to a context root using the following command:

      java -jar <OC4J_HOME>/j2ee/home/admin.jar ormi://<server>:<rmiport> <admin_username> <admin_password> -bindWebApp <earDeploymentName> <Sample_War_Name> http-web-site /<website_root>

      Example:
      java -jar D:/oc4j903/j2ee/home/admin.jar ormi://incq207a.idc.oracle.com:23791 admin welcome -bindWebApp initparams initparams http-web-site /initparams

    8. Access the servlet and JSP using the URL like the following:
    9. http://localhost:8888/initparams/servlet/ReadInitParametersServlet
      http://localhost:8888/initparams/web/readInitParamJSP.jsp


      Where localhost is your machine where OC4J instance is running. 8888 is the default port of OC4J.

    10. The URLs will invoke the Servlet/JSP that display the init parameters and its values in a HTML table.

Running the Servlet Sample Application from Oracle JDeveloper 10g:

The sample application ReadInitParams.jar can be downloaded from here. The Jar file extracts all the sample application files to a folder called ReadInitParams. Go through the following steps to run the servlet from JDeveloper.

    1. From JDeveloper, open the ReadInitParameterServlet.jws workspace file. This will open the corresponding project and source files of the application.
    2. Compile the ReadInitParameterServlet.jpr. project.
    3. Click on the ReadInitParameterServlet.java and run the file.
    4. This will execute the servlet that displays the init parameters and their values in a HTML table.
    5. Click on the readInitParamJSP.jsp and run the file.
    6. This will execute the JSP that displays the init parameters and their values in a HTML table.

Useful References

FAQ 

  1. What is the difference between the initialization parameters under the <servlet></servlet> tags, under the <context-param></context-param> and under the <filter></filter> tags in web.xml?

Context parameters are accessible to any servlet or JSP in that web-app. The common examples are email server hostname, webmasters address, some resource required by many parts of the system etc. The init-params of a servlet are specific to that servlet, example: a value that the servlet uses like an upload directory name, hit counter parameter etc..

In case of the init parameters under <filter></filter> tags, as the name suggests, it is specific to that filter and is accessible only in that filter.


Do enter your comments about this HowTo in the OTN Sample Code Discussion Forum.


How To Access/Read Init-Params in Servlets

Please rate this how-to :
Excellent
Good
Average
Below Average
Poor
E-mail this page
Printer View Printer View
Oracle Is The Information Company About Oracle | Oracle RSS Feeds | Careers | Contact Us | Site Maps | Legal Notices | Terms of Use | Privacy