A Servlet may use an object of ServletContext to communicate with the Servlet Container and access the context initialization parameters,
the MIME type of a file, dispatch requests etc. Remember, there is only object of ServletContext per application.
In this tutorial, we are going to understand how to use, set the context initialization parameters with an object of ServletContext and how to read them out.
The context initialization parameters are common and accessible to all the servlets in an application and hence are also called the application parameters.
The context initialization parameters are set in the deployment descriptor file, web.xml
Note:
ServletContext is an interface and it is a part of the Servlet API.
The full path to import and access all the methods provided by
ServletContext is
javax.servlet.ServletContext. Let us see some of its important methods.
Some methods of ServletContext
Method
Description
ObjectgetAttribute(String str)
This method gets an individual context attributes.
EnumerationgetAttributesNames()
This method gets all the named of context attributes.
voidsetAttribute(String name, Object value)
This method sets the context attributes.
voidremoveAttribute(String name)
This method sets the context attributes.
StringgetInitParameter(String str)
This method gets an individual context parameter.
EnumerationgetInitParameterNames()
This method returns all the names of the context initialization parameters.
StringgetMimeType(String file)
This method returns the MIME type of the specified file.
This method returns a RequestDispatcher object for the resource located at the given path.
Creating a webpage which calls the Servlet
We are creating a webpage which asks the user to click a button named, Yes, let's read!,
which when clicked, displays the context initialization parameters and their values mentioned in the deployment descriptor file(web.xml).
Webpage1.jsp
<html>
<head>
<title> ServletRequest Demo </title>
</head>
<body>
<b>Do you want to read Context Initialization parameters?</b>
<br/>
<br/>
<br/>
<form action = "MyServlet">
<input type = "submit" value = "Yes, let's read!" />
</form>
</body>
</html>
Using ServletContext to read context initialization parameters
Next, we are going to create a Servlet by extending the GenericServlet abstract class.
GenericServlet class implementsServlet and ServletConfig interface, hence
we can directly call the methods of ServletConfig within this newly created Servlet.
For example, we will directly call the method getServletContext()
of ServletConfig class, which creates an object of ServletContext.
By using this object of ServletContext, we are going to read the context initialization parameters common to all Servlets in the application,
by calling the following methods of ServletContext, such as -
getInitParameterNames()
getInitParameter()
MyServlet1.java
import java.io.*;
import javax.servlet.*;
import java.util.*;
public class MyServlet1 extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
{
//Getting a ServletContext object
ServletContext servCon = getServletContext();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h2> Using ServletContext object</h2> ");
//Reading one parameter
out.println("<b>Reading only one parameter its value </b> <br/>");
out.println("The Website name is " + servCon.getInitParameter("Website"));
out.println("<br/>");
out.println("<br/>");
//Reading all the parameters
out.println("</b> Reading all the parameter and their values </b> <br/>");
Enumeration enum1 = servCon.getInitParameterNames();
while(enum1.hasMoreElements())
{
String paramName = (String)enum1.nextElement();
String paramValue = servCon.getInitParameter(paramName);
out.println("Parameter "+ paramName + " has a value " + paramValue);
out.println("<br/>");
}
}
}
Advertisement
Software requirements
To execute this Servlet program, besides installing Java, we also need to install a web server i.e.
a software required to run Servlet programs. There
are number of web servers available in the market and we will install the Servlet standard - Apache Tomcat Server.
For more, please read, How to install Apache Tomcat web server.
Directory Structure of Servlet files
Let us show you through a diagram on how to structure the files for the proper execution of this program.
Project Folder - We have created a project folder named ServletContextEx within
the webapps folder of Tomcat installation folder. This folder contains the Servlet class(.java) file and WEB-INF folder.
WEB-INF - Within your project folder, you create another folder named WEB-INF and this folder should contain the deployment descriptor file(web.xml) of your Java Servlet program.
classes - Within the WEB-INF folder you should create a folder named classes. This folder should contain the compiled(.class) form of your Java Servlet class.
Creating the Deployment Descriptor file
As per the Java Servlet specifications, every web application based on Servlet must have a Deployment Descriptor file(an XML file) named web.xml.
So, let's create one -
In deployment descriptor file, <servlet> has two child tags <servlet-name> and <servlet-class> :
<servlet-name> tag is used to specify a unique name for our Servlet class, we have given it a unique name ServletConfigExample.
<servlet-class> tag is used to specify the full qualified name of the Servlet class and in our example our Servlet class is named MyServlet1.
We have also specified two context initialization parameters common to all servlets using <context-param> tag.
This tag has two child tags <param-name> and <param-value> :
<param-name> tag is used to specify the name of a parameter.
<param-value> tag is used to specify the value of this parameter associated with our Servlet class named MyServlet1.
Note:
The name of the parameters must be unique.
The child tag <servlet-name> of <servlet> tag is matched with the <servlet-name> child tag of
<servlet-mapping>. The
<url-pattern> child tag is used to specify the URL to access Servlet and we have named this URL MyServlet.
Setting the classpath
Much of the support for developing the web applications based on the Java Servlet technology does not come with the core Java.
Hence, in order to compile the Servlet programs, we have to set the classpath to a jar file named
servlet-api.jar.
This jar file provides all the classes that are required for the Servlet programming and it comes within the lib Folder of
Tomcat installation folder.
For example, in our case we have installed Tomcat Web Server within the C: Drive, hence the path to our lib folder containing the servlet-api.jar is - C:\apache-tomcat-9.0.2\lib
There are two ways to set the classpath -
You could set the classpath by entering this command at the Command Prompt, but this only temporarily sets the classpath to the path of servlet-api.jar file. If you restart your system, you will have to set the classpath again.
set classpath=C:\apache-tomcat-9.0.2\lib\servlet-api.jar
In order to set the classpath permanently, you need to set your classpath system variables. A simple tutorial on how to permanently set the classpath system variables, you may read
How to permanently set the classpath system variable
Compiling the Servlet class
After setting the classpath, you need to compile the Servlet class by entering the command at the folder where you've stored the Servlet class file.
javac -d WEB-INF/classes MyServlet1.java
Executing the Servlet
To execute our Servlet, we first need to execute the webpage containing the form, which asks the user to enter the name
and press the submit button.
As soon as the user enters the name and submits the form, the request goes to the Servlet.
Hence, you will see the URL containing the full path to the file with the request parameter -
The project folder - ServletContextEx
The url-pattern of the Servlet class declared in web.xml - MyServlet
When executed, this Servlet displays all the context initialization parameters using the methods of ServletContext object.
Please remember - These context initialization parameters are associated with the whole application and are common to all its servlets.
Servlet Initialization Parameters vs Context Initialization Parameters
While the Servlet initialization parameters are only associated and private to a specific Servlet, the context initialization parameters are common and accessible to
all the servlets in an application.
Servlet initialization parameters can be accessed by the object of ServletConfig,
while the context initialization parameters can be accessed by the object of ServletContext.