Launch your tech mastery with us—your coding journey starts now!
Course Content
Advanced Java
ServletConfig Interface

An object of ServletConfig is created by the web container for each servlet. This object can be used to get configuration information from web.xml file.

If the configuration information is modified from the web.xml file, we don’t need to change the servlet. So it is easier to manage the web application if any specific content is modified from time to time.

Advantage of ServletConfig

The core advantage of ServletConfig is that you don’t need to edit the servlet file if information is modified from the web.xml file.

Methods of ServletConfig interface
  1. public String getInitParameter(String name):Returns the parameter value for the specified parameter name.
  2. public Enumeration getInitParameterNames():Returns an enumeration of all the initialization parameter names.
  3. public String getServletName():Returns the name of the servlet.
  4. public ServletContext getServletContext():Returns an object of ServletContext.

Syntax:

public ServletConfig getServletConfig();

 

Syntax to provide the initialization parameter for a servlet

The init-param sub-element of servlet is used to specify the initialization parameter for a servlet.

<web-app>

<servlet>

    ……  

 

<init-param>

<param-name>parametername</param-name>

<param-value>parametervalue</param-value>

</init-param>

    ……  

</servlet>

</web-app>

Example of ServletConfig to get initialization parameter

In this example, we are getting the one initialization parameter from the web.xml file and printing this information in the servlet.

DemoServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

public class DemoServlet extends HttpServlet {  

public void doGet(HttpServletRequest request, HttpServletResponse response)  

    throws ServletException, IOException {  

    response.setContentType(“text/html”);  

    PrintWriter out = response.getWriter();  

    ServletConfig config=getServletConfig();  

    String driver=config.getInitParameter(“driver”);  

    out.print(“Driver is: “+driver);  

    out.close();      }  }  

web.xml

<web-app>

<servlet>

<servlet-name>DemoServlet</servlet-name>

<servlet-class>DemoServlet</servlet-class>

<init-param>

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

<param-value>com.mysql.cj.jdbc.Driver</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>DemoServlet</servlet-name>

<url-pattern>/servlet1</url-pattern>

</servlet-mapping>

</web-app>

 

Example of ServletConfig to get all the initialization parameters

In this example, we are getting all the initialization parameter from the web.xml file and printing this information in the servlet.

DemoServlet.java

import java.io.IOException;  

import java.io.PrintWriter;  

import java.util.Enumeration;  

import javax.servlet.ServletConfig;  

import javax.servlet.ServletException;  

import javax.servlet.http.HttpServlet;  

import javax.servlet.http.HttpServletRequest;  

import javax.servlet.http.HttpServletResponse;  

public class DemoServlet extends HttpServlet {  

public void doGet(HttpServletRequest request, HttpServletResponse response)  

        throws ServletException, IOException {  

    response.setContentType(“text/html”);  

    PrintWriter out = response.getWriter();  

    ServletConfig config=getServletConfig();  

    Enumeration<string> e=config.getInitParameterNames();  

    String str=””;  

    while(e.hasMoreElements()){  

    str=e.nextElement();  

    out.print(“<br>Name: “+str);  

    out.print(” value: “+config.getInitParameter(str));  

    }  

   out.close();  

}  }  

 

web.xml

<web-app>

<servlet>

<servlet-name>DemoServlet</servlet-name>

<servlet-class>DemoServlet</servlet-class>

<init-param>

<param-name>username</param-name>

<param-value>system</param-value>

</init-param>

<init-param>

<param-name>password</param-name>

<param-value>oracle</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>DemoServlet</servlet-name>

<url-pattern>/servlet1</url-pattern>

</servlet-mapping>

</web-app>

ServletContext Interface

An object of ServletContext is created by the web container at time of deploying the project. This object can be used to get configuration information from web.xml file. There is only one ServletContext object per web application.If any information is shared to many servlet, it is better to provide it from the web.xml file using the<context-param> element.

Advantage of ServletContext

Easy to maintain if any information is shared to all the servlet, it is better to make it available for all the servlet. We provide this information from the web.xml file, so if the information is changed, we don’t need to modify the servlet. Thus it removes maintenance problem.

Usage of ServletContext Interface

There can be a lot of usage of ServletContext object. Some of them are as follows:

  1. The object of ServletContext provides an interface between the container and servlet.
  2. The ServletContext object can be used to get configuration information from the web.xml file.
  3. The ServletContext object can be used to set, get or remove attribute from the web.xml file.
  4. The ServletContext object can be used to provide inter-application communication.
Commonly used methods of ServletContext interface

There is given some commonly used methods of ServletContext interface.

  1. public String getInitParameter(String name):Returns the parameter value for the specified parameter name.
  2. public Enumeration getInitParameterNames():Returns the names of the context’s initialization parameters.
  3. public void setAttribute(String name,Object object):sets the given object in the application scope.
  4. public Object getAttribute(String name):Returns the attribute for the specified name.
  5. public Enumeration getInitParameterNames():Returns the names of the context’s initialization parameters as an Enumeration of String objects.
  6. public void removeAttribute(String name):Removes the attribute with the given name from the servlet context.
How to get the object of ServletContext interface
  1. getServletContext() method of ServletConfig interface returns the object of ServletContext.
  2. getServletContext() method of GenericServlet class returns the object of ServletContext.

Syntax:

public ServletContext getServletContext()

Syntax to provide the initialization parameter in Context scope

The context-param element, subelement of web-app, is used to define the initialization parameter in the application scope. The param-name and param-value are the sub-elements of the context-param. The param-name element defines parameter name and and param-value defines its value.

<web-app>

 ……  

 

<context-param>

<param-name>parametername</param-name>

<param-value>parametervalue</param-value>

</context-param>

 ……  

</web-app>

Example of ServletContext to get the initialization parameter

In this example, we are getting the initialization parameter from the web.xml file and printing the value of the initialization parameter. Notice that the object of ServletContext represents the application scope. So if we change the value of the parameter from the web.xml file, all the servlet classes will get the changed value. So we don’t need to modify the servlet. So it is better to have the common information for most of the servlets in the web.xml file by context-param element. Let’s see the simple example:

 

DemoServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

public class DemoServlet extends HttpServlet{  

public void doGet(HttpServletRequest req,HttpServletResponse res)  

throws ServletException,IOException  

{  

res.setContentType(“text/html”);  

PrintWriter pw=res.getWriter();  

//creating ServletContext object  

ServletContext context=getServletContext();  

//Getting the value of the initialization parameter and printing it  

String driverName=context.getInitParameter(“dname”);  

pw.println(“driver name is=”+driverName);  

pw.close();  

 }}  

web.xml

<web-app>

<servlet>

<servlet-name>servlet1</servlet-name>

<servlet-class>DemoServlet</servlet-class>

</servlet>

<context-param>

<param-name>dname</param-name>

<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>

</context-param>

<servlet-mapping>

<servlet-name>servlet1</servlet-name>

<url-pattern>/context</url-pattern>

</servlet-mapping>

</web-app>

 

Example of ServletContext to get all the initialization parameters

In this example, we are getting all the initialization parameter from the web.xml file. For getting all the parameters, we have used the getInitParameterNames() method in the servlet class.

 

DemoServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

 

public class DemoServlet extends HttpServlet{  

public void doGet(HttpServletRequest req,HttpServletResponse res)  

throws ServletException,IOException  

{  

res.setContentType(“text/html”);  

PrintWriter out=res.getWriter();  

ServletContext context=getServletContext();  

Enumeration<string> e=context.getInitParameterNames();  

String str=””;  

while(e.hasMoreElements()){  

    str=e.nextElement();  

    out.print(“<br> “+context.getInitParameter(str));  

}  }}  

web.xml

<web-app>

<servlet>

<servlet-name>servlet1</servlet-name>

<servlet-class>DemoServlet</servlet-class>

</servlet>

<context-param>

<param-name>dname</param-name>

<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>

</context-param>

 

<context-param>

<param-name>username</param-name>

<param-value>system</param-value>

</context-param>

 

<context-param>

<param-name>password</param-name>

<param-value>oracle</param-value>

</context-param>

 

<servlet-mapping>

<servlet-name> servlet1</servlet-name>

<url-pattern>/context</url-pattern>

</servlet-mapping>

 

</web-app>

Attribute in Servlet

An attribute is an object that can be set, get or removed from one of the following scopes:

  1. request scope
  2. session scope
  3. application scope

The servlet programmer can pass informations from one servlet to another using attributes. It is just like passing object from one class to another so that we can reuse the same object again and again.

Attribute specific methods of ServletRequest, HttpSession and ServletContext interface

There are following 4 attribute specific methods. They are as follows:

  1. public void setAttribute(String name,Object object):sets the given object in the application scope.
  2. public Object getAttribute(String name):Returns the attribute for the specified name.
  3. public Enumeration getInitParameterNames():Returns the names of the context’s initialization parameters as an Enumeration of String objects.
  4. public void removeAttribute(String name):Removes the attribute with the given name from the servlet context.
Example of ServletContext to set and get attribute

In this example, we are setting the attribute in the application scope and getting that value from another servlet.

 

DemoServlet1.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

 

public class DemoServlet1 extends HttpServlet{  

public void doGet(HttpServletRequest req,HttpServletResponse res)  

{  

try{  

res.setContentType(“text/html”);  

PrintWriter out=res.getWriter();  

 

ServletContext context=getServletContext();  

context.setAttribute(“company”,”IBM”);  

 

out.println(“Welcome to first servlet”);  

out.println(“<a href=’servlet2′>visit</a>”);  

out.close();  

 

}catch(Exception e){out.println(e);}  

}}  

DemoServlet2.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

public class DemoServlet2 extends HttpServlet{  

public void doGet(HttpServletRequest req,HttpServletResponse res)  

{  

try{  

res.setContentType(“text/html”);  

PrintWriter out=res.getWriter();  

 

ServletContext context=getServletContext();  

String n=(String)context.getAttribute(“company”);  

out.println(“Welcome to “+n);  

out.close();  

}catch(Exception e){out.println(e);}  

}}  

web.xml

<web-app>

<servlet>

<servlet-name>s1</servlet-name>

<servlet-class>DemoServlet1</servlet-class>

</servlet>

 

<servlet-mapping>

<servlet-name>s1</servlet-name>

<url-pattern>/servlet1</url-pattern>

</servlet-mapping>

 

<servlet>

<servlet-name>s2</servlet-name>

<servlet-class>DemoServlet2</servlet-class>

</servlet>

 

<servlet-mapping>

<servlet-name>s2</servlet-name>

<url-pattern>/servlet2</url-pattern>

</servlet-mapping>

</web-app>

Difference between ServletConfig and ServletContext:

ServletConfig

  • ServletConfig available in javax.servlet.*; package
  • ServletConfig object is one per servlet class
  • Object of ServletConfig will be created during initialization process of the servlet
  • This Config object is public to a particular servlet only
  • Scope: As long as a servlet is executing, ServletConfig object will be available, it will be destroyed once the servlet execution is completed.
  • We should give request explicitly, in order to create ServletConfig object for the first time
  • In web.xml – <init-param> tag will be appear under <servlet-class> tag

ServletContext

  • ServletContext available in javax.servlet.*; package
  • ServletContext object is global to entire web application
  • Object of ServletContext will be created at the time of web application deployment
  • Scope: As long as web application is executing, ServletContext object will be available, and it will be destroyed once the application is removed from the server.
  • ServletContext object will be available even before giving the first request
  • In web.xml – <context-param> tag will be appear under <web-app> tag

So finally…….

No. of web applications  =  That many number of ServletContext objects [ 1 per web application ]
No. of servlet classes = That many number of ServletConfig objects