ServletContext Interafce in Java

Introduction

This article explains the ServletContext Interface in Java. NetBeans IDE is used to develop the sample program.

What is ServletContext interface

ServletConfig creates an object of ServletContext then used it in a servlet to deploy it on the server the same as in ServletConfig, but it has one important feature that makes it more useful; it can manage more than one Servlet. That is not possible with the ServletConfig interface.

It exists in the javax.servlet.ServletContext package; this interface is provided by the Servlet API. Implementation of it is provided by the Servlet vendor. An object of Servlet type context is created by the server at the time of deployment of it.

Advantages

1. Easy to maintain

If in an application we need to create more then one servlet then we need to share their information in the web.xml. So in that context if there is any change in any one of the servlets then we need to change all the servlets and also need to change the information in web.xml. So in that scenario the Servlet vendors provide ServletContext objects that are common to all, hence if there are changes in any servlet then we need to change only the web.xml file. So it provides easier maintenance.

2. Handling large applications

Sometimes a large application is divided into multiple smaller applications. All these applications are deployed on the server as a part of a single application. These smaller apps are dependent on each other and need to frequently forward requests among them. Such request forwarding is called "inter-application forwarding". This is provided by the ServletContext interface.

Some Usage

A ServletContext Object has several usages, some of them are:

  • They can be used to provide inter-application communication.
  • This object can be used to set, get or remove attributes from the web.xml file.
  • They provide an interface between the container and servlet.
  • This object is used to get configuration information from the web.xml file and provide it to the server.

Some commonly used public methods of ServletContext are:

  • getServletContext()

          Method of ServletConfig used to return the object of ServletContext.

  • getServletContext()

          Method of GenericServlet class used to return the object of ServletContext.

Syntax

public ServletContext getServletContext

Some additional methods of ServletContext are:

1. setAttribute()

Stores an attribute in application scope.

Syntax

public void setAttribute(String name, Object attribute);

2. getAttribute()

Obtains the value of an attribute from application scope.

3. getAttributeNames()

Obtains the name of all application scope attributes.

Syntax

public Enumeration getAttributeNames();

4. removeAttribute()

Removes an attribute.

Syntax

public boolean removeAttribute(String name);

5. getRequestDispatcher()

Obtains a RequestDispatcher object for a resource.

Syntax

public RequestDispatcher getRequestDispatcher(String url of resource);

6. getContext()

Obtains a reference of a ServletContext object of a specified application.

Syntax

public ServletContext getServletContext(String app.nmae);

7. getRealPath()

Obtains the actual path of the file folder from the server.

Syntax

public String getRealPath();

Example

//We can get the ServletContext object from ServletConfig object.
ServletContext appl=getServletConfig().getServletContext();

//Another convenient way to get the ServletContext object.
ServletContext appl=getServletContext();

Syntax of web.xml

<web-app>
  ..................

<servlet>
<servlet-name>ServletName</servlet-name>
<servlet-class>ServletClass</servlet-class>
</servlet>

<context-param>
   <param-name>param-name</param-name>
   <param-value>param-value</param-value>

</context-param>
  .............
</web-app>

Example

Let's take a simple example. In this example we are creating a single servlet file ("ContextDemo.java"). This Servlets carries the information from the web.xml file and displays it to the user. For making the user interface we create a HTML file ("index.html") that contains a link to a servlet file. When the user clicks on that file, the servlet is executed and displays information that they receive from the web.xml to the user. Remember that the object of ServletContext represents the application scope. So we used a common interface context-param in the web.xml file to provide better maintenance.

The following procedure needs to be used.

Step 1

Open the NetBeans IDE.

Fig-1.jpg

Step 2

Choose "Java web" -> "Web application" as shown below.

Fig-2.jpg

Step 3

Now enter your project name as "ServletContextDemo" and click on "Next" as shown below.

Fig-3.jpg

Step 4

Now choose your server and Java version installed on your system and then click on "Finish" as shown below.

Fig-4.jpg

Step 5

Now delete your default index.jsp file and create a new index.html file as shown below.

Fig-5.jpg

Step 6

Now type your file name as "index" as shown below.

Fig-6.jpg

Step 7

Now provide the following code for it.

<html>

    <head>

        <title>TODO supply a title</title>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <meta name="viewport" content="width=device-width">

    </head>

    <body>

    <center><h1>Click on below link to get driver detail</h1>

        <a href="ContextDemo">Click To View</a>

    </body>

</html> 

Fig-7.jpg

Step 8

Now create a servlet named "ContextDemo" and write the following code for it.

ContextDemo.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class ContextDemo extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        ServletContext context = getServletContext();

        String driver = context.getInitParameter("driver");

        out.print("Oracle Driver is: " + driver);

        out.close();

    }

} 

Fig-8.jpg

Step 9

Now replace the code of your default web.xml file with the following code.

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <servlet>

        <servlet-name>ContextDemo</servlet-name>

        <servlet-class>ContextDemo</servlet-class>

    </servlet>

    <context-param>

        <param-name>driver</param-name>

        <param-value>oracle.jdbc.driver.OracleDriver</param-value>

    </context-param>       

 

    <servlet-mapping>

        <servlet-name>ContextDemo</servlet-name>

        <url-pattern>/ContextDemo</url-pattern>

    </servlet-mapping>   

</web-app> 

Fig-9.jpg

Step 10

Now our application is ready.

Right-click on the "Project" menu then select "run". The following output is generated:

Fig-10.jpg

Now click on the given link.

Fig-11.jpg


Similar Articles