Open In App

Difference between ServletConfig and ServletContext in Java Servlet

ServletConfig and ServletContext, both are objects created at the time of servlet initialization and used to provide some initial parameters or configuration information to the servlet. But, the difference lies in the fact that information shared by ServletConfig is for a specific servlet, while information shared by ServletContext is available for all servlets in the web application. ServletConfig:

ServletContext:



Implementation of examples of ServletConfig and ServletContext is shown below. 

web.xml



 




import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
public class Recruiter extends HttpServlet {
 
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException
    {
        String email
            = getServletConfig()
                  .getInitParameter("Email");
        String website
            = getServletContext()
                  .getInitParameter("Website-name");
        PrintWriter out = response.getWriter();
        out.println("<center><h1>" + website
                    + "</h1></center><br><p>Contact us:"
                    + email);
    }
}




import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
 
public class Applicant extends HttpServlet {
 
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException
    {
 
        String email
            = getServletConfig()
                  .getInitParameter("Email");
        String website
            = getServletContext()
                  .getInitParameter("Website-name");
        PrintWriter out = response.getWriter();
        out.println("<center><h1>" + website
                    + "</h1></center><br><p>Contact us:"
                    + email);
    }
}

Below is the table of comparison between the two:

ServletConfig ServletContext
ServletConfig is servlet specific ServletContext is for whole application
Parameters of servletConfig are present as name-value pair in <init-param> inside <servlet>. Parameters of servletContext are present as name-value pair in <context-param> which is outside of <servlet> and inside <web-app>
ServletConfig object is obtained by getServletConfig() method. ServletContext object is obtained by getServletContext() method.
Each servlet has got its own ServletConfig object. ServletContext object is only one and used by different servlets of the application.
Use ServletConfig when only one servlet needs information shared by it. Use ServletContext when whole application needs information shared by it

Article Tags :