In this article I will show you – How to work with Initialization and Context Initialization Parameters. In a single Dynamic Web Project I will demonstrate for both kind of servlets 1. GenericServlet and 2. HttpServlet.
What are the initialization parameters in Servlet?
Initialization parameters are loaded or started when a web container starts (web.xml is loaded). There are 2 type of initializing the parameters.
1. Servlet Initialization Parameters
These parameters are defined within <servlet></servlet> and after <servlet-class></servlet-class> tag. These initialization parameters will be initialized when the particular Servlet will be initialized. These parameters are accessible to the Servlet in which they are defined.
<servlet>
<description></description>
<display-name>ShowInitParametersHttpServlet</display-name>
<servlet-name>ShowInitParametersHttpServlet</servlet-name>
<servlet-class>com.sitenol.ServletInitParameters.ShowInitParametersHttpServlet</servlet-class>
<init-param>
<param-name>admin-email</param-name>
<param-value>sitenol@gmail.com</param-value>
</init-param>
<init-param>
<param-name>admin-phone</param-name>
<param-value>9959056098</param-value>
</init-param>
<init-param>
<param-name>admin-name</param-name>
<param-value>Anthony</param-value>
</init-param>
</servlet>
2. Servlet Context Parameters
These parameters will be initialized when deployment descriptor (web.xml) will be loaded. These parameters are accessible to all the Servlets defined in the same web.xml. They are accessible at application level.
<context-param>
<param-name>company-name</param-name>
<param-value>Sitenol.com</param-value>
</context-param>
Why are the initialization parameters required in Servlet?
Initialization parameters are used to reduce the compilation cycle of Servlet. It reduces our coding effort.
How to Retrieve Initialization Parameters Name and Value ?
The Servlet initialization parameters are retrieved by using ServletConfig object. There are 2 methods given by ServletConfig class to get the name and value of the initialization parameters.
1. String getInitParameter(String paramName) : This method returns the value of the parameter named “paramName”. In case this parameter is not available in the web.xml file, it will return null value.
2. Enumeration getInitParameterNames() : This method returns names of context initialization parameters as Enumeration of String objects. It will return empty Enumeration or null in case no context initialization parameter is available.
How to retrieve Context Initialization Parameters ?
The Context initialization parameters are retrieved by using ServletContext object. We can get ServletContext object by
ServletContext servletContext = servletConfig.getServletContext();
Here “servletConfig” is the reference of ServletConfig object.
1. String getInitParameter(String paramName) : This method returns the value of the parameter named “paramName”. In case this parameter is not available in the web.xml file, it will return null value.
2. Enumeration getInitParameterNames() : This method returns names of context initialization parameters as Enumeration of String objects. It will return empty Enumeration or null in case no context initialization parameter is available.
A simple example of Initialization Paramater Using GenericServlet and HttpServlet
In this example I am going to demonstrate the initialization parameters using 1. javax.servlet.GenericServlet and 2. javax.servlet.http.HttpServlet class.
Workspace Screenshot :
1. Create one httpServletInitTest.html page : This HTML page is degined to demonstrate the initialization
ways in javax.servlet.http.HttpServlet.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="ShowInitParametersHttpServlet" method="post">
<input type="submit"
value="Show InitParameters for ShowInitParametersHttpServlet Servlet">
</form>
</body>
</html>
2. Create one genericServletInitTest.html page : This HTML page is degined to demonstrate the initialization ways using
javax.servlet.GenericServlet.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="ShowInitParametersGenericServlet" method="get">
<input type="submit"
value="Show InitParameters for ShowInitParametersGenericServlet Servlet">
</form>
</body>
</html>
3. Create One ShowInitParametersHttpServlet.java Servlet : Code for HTTP Servlet demonstration.
package com.sitenol.ServletInitParameters;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ShowInitParametersHttpServlet
*/
public class ShowInitParametersHttpServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
ServletConfig servletConfig;
/**
* @see HttpServlet#HttpServlet()
*/
public ShowInitParametersHttpServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init(config);
this.servletConfig = config;
}
/**
* @see Servlet#getServletConfig()
*/
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}
/**
* @see Servlet#getServletInfo()
*/
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
Enumeration<String> paramNames = (Enumeration) this.servletConfig
.getInitParameterNames();
out.print("<html><body> Getting List of Init Param Values using javax.servlet.http.HttpServlet");
out.print("<table border='1'>");
while (paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
System.out.println(paramName);
out.print("<tr><td>" + paramName + "</td><td>"
+ (String) this.servletConfig.getInitParameter(paramName)
+ "</td></tr>");
}
out.print("</table><br/>");
out.print("Getting List of Init Context Param Values using javax.servlet.http.HttpServlet");
out.print("<table border='1'>");
ServletContext servletContext = this.servletConfig.getServletContext();
Enumeration<String> contextParamNames = (Enumeration) servletContext
.getInitParameterNames();
while (contextParamNames.hasMoreElements()) {
String contextParamName = (String) contextParamNames.nextElement();
System.out.println(contextParamName);
out.print("<tr><td>"
+ contextParamName
+ "</td><td>"
+ (String) servletContext
.getInitParameter(contextParamName) + "</td></tr>");
}
out.print("</table>");
out.print("</body></html>");
}
}
4. Create One ShowInitParametersGenericServlet.java Servlet : Code for Generic Servlet demonstration.
package com.sitenol.ServletInitParameters;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* Servlet implementation class ShowInitParametersGenericServlet
*/
public class ShowInitParametersGenericServlet extends GenericServlet {
private static final long serialVersionUID = 1L;
ServletConfig servletConfig;
/**
* @see GenericServlet#GenericServlet()
*/
public ShowInitParametersGenericServlet() {
super();
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
this.servletConfig = config;
}
/**
* @see Servlet#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Servlet#getServletConfig()
*/
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}
/**
* @see Servlet#getServletInfo()
*/
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}
/**
* @see Servlet#service(ServletRequest request, ServletResponse response)
*/
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
Enumeration<String> paramNames = (Enumeration) this.servletConfig
.getInitParameterNames();
out.print("<html><body>Getting List of Init Param Values using javax.servlet.GenericServlet");
out.print("<table border='1'>");
while (paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
System.out.println(paramName);
out.print("<tr><td>" + paramName + "</td><td>"
+ (String) this.servletConfig.getInitParameter(paramName)
+ "</td></tr>");
}
out.print("</table><br/>");
out.print("Getting List of Init Context Param Values using javax.servlet.GenericServlet");
out.print("<table border='1'>");
ServletContext servletContext = this.servletConfig.getServletContext();
Enumeration<String> contextParamNames = (Enumeration) servletContext
.getInitParameterNames();
while (contextParamNames.hasMoreElements()) {
String contextParamName = (String) contextParamNames.nextElement();
System.out.println(contextParamName);
out.print("<tr><td>"
+ contextParamName
+ "</td><td>"
+ (String) servletContext
.getInitParameter(contextParamName) + "</td></tr>");
}
out.print("</table>");
out.print("</body></html>");
}
}
5. Configure init params in web.xml file (deployment Descriptor) : In the web.xml file we will configure the initialization and context initialization parameters for both 1. javax.servlet.GenericServlet and 2. javax.servlet.http.HttpServlet Servlets.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>ServletInitializationParameters</display-name>
<welcome-file-list>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>ShowInitParametersGenericServlet</display-name>
<servlet-name>ShowInitParametersGenericServlet</servlet-name>
<servlet-class>com.sitenol.ServletInitParameters.ShowInitParametersGenericServlet</servlet-class>
<init-param>
<param-name>admin-email</param-name>
<param-value>sitenol@gmail.com</param-value>
</init-param>
<init-param>
<param-name>admin-phone</param-name>
<param-value>9959056098</param-value>
</init-param>
<init-param>
<param-name>admin-name</param-name>
<param-value>Anthony</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ShowInitParametersGenericServlet</servlet-name>
<url-pattern>/ShowInitParametersGenericServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>ShowInitParametersHttpServlet</display-name>
<servlet-name>ShowInitParametersHttpServlet</servlet-name>
<servlet-class>com.sitenol.ServletInitParameters.ShowInitParametersHttpServlet</servlet-class>
<init-param>
<param-name>admin-email</param-name>
<param-value>admin@gmail.com</param-value>
</init-param>
<init-param>
<param-name>admin-phone</param-name>
<param-value>99876777</param-value>
</init-param>
<init-param>
<param-name>admin-name</param-name>
<param-value>Tarun</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ShowInitParametersHttpServlet</servlet-name>
<url-pattern>/ShowInitParametersHttpServlet</url-pattern>
</servlet-mapping>
<context-param>
<param-name>company-name</param-name>
<param-value>Sitenol.com</param-value>
</context-param>
<context-param>
<param-name>company-address</param-name>
<param-value>9320 Annapolis Road, Suite 310, Lanham, MaryLand, 20706, USA</param-value>
</context-param>
<context-param>
<param-name>company-phone</param-name>
<param-value>0044-906555</param-value>
</context-param>
</web-app>
6. Run the Application : We will run the application using 2 urls so that we can demonstarte both kind of Servlets.
URL to see the results for Generic Servlet class
http://localhost:8080/ServletInitializationParameters/genericServletInitTest.html
URL to see the results for HTTP Servlet class
http://localhost:8080/ServletInitializationParameters/httpServletInitTest.html
Thanks for reading this article. Please let me know your feedback. In case of any compilation error, run time error please feel free to drop a comment.