In this article, we are going to understand how to associate attributes with a ServletContext object. An attribute is an object and when
such objects are associated with a ServletContext object, they are called context attributes and are available to the whole application i.e.
all the Servlets in the application can access these attributes through the ServletContext object.
These context attributes are stored in the context scope on the server side used for the request processing.
We can set and get the value of context attributes associated with the ServletContext object
by using the methods of
ServletContext interface.
After setting some attributes with the ServletContext object, we can even access these attributes from one to another Servlet in order to have a shared request processing by multiple Servlets.
Methods of ServletContext to set,get and remove context attributes
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.
A Request Attribute Example
We are creating a webpage which asks the user to submit
asking the user to enter the name and percentage
at high school to know if he/she is eligible to get a scholarship at an university or not, based on a condition -
A user must have a percentage of more than 90
after filling the details when submit button is clicked, the request is are dispatched or forwarded to the Servlet named FirstServlet (mentioned in the deployment descriptor file(web.xml).
Webpage1.jsp
<html>
<head>
<title> Context Attributes Demo </title>
</head>
<body>
<b>Please enter your details to know if you are eligible to apply for scholarship at our university.</b>
<br/>
<br/>
<br/>
<form action = "FirstServlet">
Name :<input type = "text" name = "username"/>
Percentage :<input type = "text" name = "percentile"/>
<input type = "submit" value = "submit" />
</form>
</body>
</html>
Creating a Servlet to set request attributes
We are creating a Servlet extending GenericServlet abstract class.
GenericServlet class implementsServlet and ServletConfig interface, hence
we can directly call the methods of ServletConfig within this Servlet.
In this Servlet class named MyServlet1.java, we have implemented the service(ServletRequest req, ServletResponse res)
of GenericServlet. Within the service() method, we have created to context attributes named
Name and Percent and have set them with the ServletContext object using the method setAttribute() method of ServletContext.
Next, by using the ServletContext object we have called its method getRequestDispatcher(String path) method to create an an object of RequestDispatcher.
If the pencentage of the user is less than 90,
then by using the object of RequestDispatcher, we are going to call its method
forward(ServletRequest req, ServletResponse res) to forward the current request and the context attributes from the current Servlet
named FirstServlet to another Servlet named SecondServlet, as mentioned in the deployment descriptor file(web.xml)
If the Salary of the user is greater than 5000,
then by using the object of RequestDispatcher, we are going to call its method forward(ServletRequest req, ServletResponse res)
to forward the current request and context attributes from the current Servlet named FirstServlet to another Servlet named ThirdServlet, as mentioned in the deployment descriptor file(web.xml)
MyServlet1.java
import java.io.*;
import javax.servlet.*;
public class MyServlet1 extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
{
//Creating ServletContext object
ServletContext servCon = getServletContext();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Using ServletContext object to set and read context attributes");
//Setting Request Attributes to be shared between multiple servlets
servCon.setAttribute("Name", request.getParameter("username"));
servCon.setAttribute("Percent", request.getParameter("percentile"));
if(new Integer(servCon.getAttribute("Percent")) <90)
{
RequestDispatcher reqDispatch = servCon.getRequestDispatcher("/SecondServlet");
reqDispatch.forward(request,response);
}
else
{
RequestDispatcher reqDispatch = servCon.getRequestDispatcher("/ThirdServlet");
reqDispatch.forward(request,response);
}
}
}
MyServlet2.java
import java.io.*;
import javax.servlet.*;
public class MyServlet2 extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
{
ServletContext servCon = getServletContext();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<b>" + "Hello " + servCon.getAttribute("Name") + "," + "</b>");
out.println("<br/>");
out.println("<br/>");
out.println("<br/>");
out.println("<br/>");
out.println("<b>Sorry, you are not eligible to get a scholarship at our university </b>");
out.println("<b>, because your percentage of " + servCon.getAttribute("Salary") + " does not meet our criteria.<b>");
}
}
MyServlet3.java
import java.io.*;
import javax.servlet.*;
public class MyServlet3 extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
{
ServletContext servCon = getServletContext();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<b>" + "Hello " + servCon.getAttribute("Name") + "," + "</b>");
out.println("<br/>");
out.println("<br/>");
out.println("<br/>");
out.println("<br/>");
out.println("<b>Congratulations, you are eligible to get a scholarship at our university, <b>");
out.println("<b> because your percentage of " + servCon.getAttribute("Salary") + " meets our criteria.</b>");
}
}
Advertisement
Directory Structure of Servlet files
The diagram above depicts how to arrange the Servlet files in a specific directory structure, as per Java Servlet Specification-
Project Folder - We have created a project folder named ServletContextAttributesEx 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.
<servlet-class> tag is used to specify the full qualified name of the Servlet class .
Note
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, Hence -
We have named this URL FirstServlet. to access the first servlet, MyServlet1.java
We have named this URL SecondServlet to access the second servlet, MyServlet2.java.
We have named this URL ThirdServlet to access the third servlet, MyServlet3.java.
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 both of 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
javac -d WEB-INF/classes MyServlet2.java
javac -d WEB-INF/classes MyServlet3.java
Executing the Servlet
First we execute the webpage containing the form, asking the user to enter the name and percentage
at high school to know if he/she is eligible to get a scholarship at an university or not.
As soon as the user submits the form, the request goes to the Servlet named FirstServlet which checks if you are eligible
to get a scholarship or not.
If you are not eligible, then the current request and the context attribute are forwarded using forward() method
to the second servlet named SecondServlet. Within the SecondServlet, by reading the context attributes an appropriate
message is shown.
if you are eligible, then the current request and its attributes are forwarded to the third servlet named ThirdServlet,
Within the ThirdServlet, by reading the context attributes an appropriate congratulatory message is displayed to the user.