javax.servlet.ServletContext Interface :-


ServletContext is used to share data between different parts (between different servlet's and jsp's)of our web application. In contrast with ServletConfig, one ServetContext is created for the complete web application that is shared by all the servlets and jsp in application.
ServletContext can also be used to get configuration information related to entire application from web.xml file.
ServletContext is created by container at the time of deployment of application and make it available for all the servlets and jsp available in web application.

Getting reference to ServletContext -

ServletContext is available within ServletConfig. We can create object of ServletContext by using ServletConfig, getServletContext() method as follows -
ServletConfig sc = getServletConfig();
ServletContext application = sc.getServletContext();
OR
ServletContext application = getServletConfig().getServletContext();


Methods of ServletContext -

Some important methods of ServletContext are as follows -
Method name with return type Description
1- public String getInitParameter(String paramName) - This method is used to get the value of context parameter whose name is specified by paramName in web.xaml file.
2- public java.util.Enumeration<String> getInitParameterNames() This method is used to get the names of context parameters specified in web.xml file. It returns parameter names as Enumeration of String type.
3- public void setAttribute(String Attribute_name, Object Attribute_value) This method is used to add an attribute to ServletContext, whose name and value are specified by Attribute_name and Attribute_value. If attribute of the same name exists previously, then it will replace the old value of attribute with this new value.
4- Object getAttribute(String Attribute_name) This method returns the value of attribute as Object, whose name is specified by Attribute_name.
5- java.util.Enumeration<String> getAttributeNames() This method returns names of all attribute available in ServletContext.


Example 1 -

This example will show you how to access configuration information related to entire application from web.xml using ServletContext.

1 - index.html or index.jsp - This will be your default page.
<!DOCTYPE html>
<html>
    <head>
        <title>ServletContext Demo</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h1>ServletContext Demo</h1>
        <a href="FirstServ">Get ServletCotext info from First Servlet</a>
        <br>
        <a href="SecondServ">Get ServletCotext info from Second Servlet</a>
    </body>
</html>    

2- Create a package named servs and within servs create two servlets named FirstServ and SecondServ.
Add the following code in servlets -
FirstServ Servlet -

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServ extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
       try
       {
         PrintWriter out = response.getWriter();
         out.println("<h1>First Servlet</h1>");
         ServletContext application = getServletConfig().getServletContext();
         String nm = application.getInitParameter("Name");
         String email = application.getInitParameter("Email");
         out.println("Name is - "+ nm + "<br>");
         out.println("Email is - "+ email + "<br>");
         
         out.println("Parameters names are - ");
         java.util.Enumeration<String> enu = application.getInitParameterNames();
         while(enu.hasMoreElements())
         {
             out.println(enu.nextElement() + "<br>");
         }
       }
       catch(Exception ex)
       {
           System.out.println(ex);
       }
    }
}    

SecondServ Servlet -

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SecondServ extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try
        {
         PrintWriter out = response.getWriter();
         out.println("<h1>Second Servlet</h1>");
         ServletContext application = getServletConfig().getServletContext();
         String nm = application.getInitParameter("Name");
         String email = application.getInitParameter("Email");
         out.println("Name is - "+ nm + "<br>");
         out.println("Email is - "+ email + "<br>");
         
         out.println("Parameter names are - ");
         java.util.Enumeration<String> enu = application.getInitParameterNames();
         while(enu.hasMoreElements())
         {
             out.println(enu.nextElement() + "<br>");
         } 
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}    
3- web.xml (Deployment Descriptor) - Add the following code to web.xml file -
<web-app>
    <servlet>
        <servlet-name>FirstServ</servlet-name>
        <servlet-class>servs.FirstServ</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>SecondServ</servlet-name>
        <servlet-class>servs.SecondServ</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>FirstServ</servlet-name>
        <url-pattern>/FirstServ</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>SecondServ</servlet-name>
        <url-pattern>/SecondServ</url-pattern>
    </servlet-mapping>
    
    <context-param>
        <param-name>Name</param-name>
        <param-value>Tom</param-value>
    </context-param>
    <context-param>
        <param-name>Email</param-name>
        <param-value>Tom@gettechnotes.com</param-value>
    </context-param>
    
</web-app>
Note - <context-param> shoud be outside of all servlets and within <web-app> tag.
4- Now run your project and it will show you the following output -



When you will click on the first link, it will show you the context information of application -



And when you will click on the second link, it will again show you the context information of application -



So it is clear from above that there exists one ServletContext per web application and all servlet's and jsp's share the same ServletContext.

Example 2 -

This example will show you how to share data between different parts of application using setAttribute() and getAttribute() methods of ServletContext.

index.html or index.jsp - This will be your default page.
<!DOCTYPE html>
<html>
    <head>
        <title>ServletContextDemo_2</title>
    </head>
    <body>
        <form method="post" action="FirstServ">
        <table border="1px">
            <tr>
                <td>Name - </td>
                <td><input type="text" name="t1"></td>
            </tr>
            <tr>
                <td>Value - </td>
                <td><input type="text" name="t2"></td>
            </tr>
            <tr>
                <td><input type="submit" value="Add"></td>
                <td><a href="SecondServ">Show Context Information</a></td>
            </tr>
        </table>
            </form>
    </body>
</html>    

2- Create a package named servs and within servs create two servlets named FirstServ and SecondServ.
Add the following code in servlets -
FirstServ Servlet -

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServ extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try
        {
            PrintWriter out = response.getWriter();
            ServletContext application = getServletConfig().getServletContext();
            String name = request.getParameter("t1");
            String value = request.getParameter("t2");
            application.setAttribute(name, value);
            response.sendRedirect("index.html");
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}    

SeconServ Servlet -

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SecondServ extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try
        {
            PrintWriter out = response.getWriter();
            ServletContext application = getServletConfig().getServletContext();
            java.util.Enumeration enu = application.getAttributeNames();
            while(enu.hasMoreElements())
            {
                String name = enu.nextElement();
                String val = application.getAttribute(name).toString();
                out.println("Attribute name - " +name+ " Attribute value - "+val);                
            }
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}        

3- web.xml - Add the following code to web.xml -
<web-app>
    <servlet>
        <servlet-name>FirstServ</servlet-name>
        <servlet-class>servs.FirstServ</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>SecondServ</servlet-name>
        <servlet-class>servs.SecondServ</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>FirstServ</servlet-name>
        <url-pattern>/FirstServ</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>SecondServ</servlet-name>
        <url-pattern>/SecondServ</url-pattern>
    </servlet-mapping>
</web-app>        

4 - Now run the project.