Explain ServletConfig and ServletContext

Explain ServletConfig and Servlet Context

ServletConfig

  • Scope: Specific to a single servlet.
  • Purpose: Used to pass initialization parameters to the servlet during its initialization.
  • Lifecycle: Created once when the servlet is initialized and destroyed when the servlet is destroyed.

Methods

  1.   String getServletName(): Returns the name of the servlet.
  2.   Servlet Context getServlet-Context(): Returns the Servlet Context object.
  3.   String getInitParameter(String name): Returns the value of the specified initialization parameter.
  4.   Enumeration<String> getInitParameterNames(): Returns an enumeration of all initialization parameter names.

ServletContext

  • Scope : Shared among all servlets in a web application.
  • Purpose : Used to provide information about the web application environment and to share data between servlets.
  • Lifecycle : Created when the web application is deployed and destroyed when the web application is undeployed or the server is shut down.

Methods

  • String getContextPath(): Returns the context path of the web application.
  • String getInitParameter(String name): Returns the value of the specified context-wide initialization parameter.
  • Enumeration<String> getInitParameterNames(): Returns an enumeration of all context-wide initialization parameter names.
  • Object getAttribute(String name): Returns the attribute with the specified name.
  • void setAttribute(String name, Object object): Binds an object to a given attribute name.
  • RequestDispatcher getRequestDispatcher(String path): Returns a RequestDispatcher object for the specified path.
  • void log(String msg): Logs a message to the servlet container’s log file.

ServletConfig and ServletContext

Deployment Descriptor (web.xml) :
Java Example
1.  Deployment Descriptor (web.xml) :
    xml
    <web-app>
        <context-param>
            <param-name>globalParam</param-name>
            <param-value>globalValue</param-value>
        </context-param>
        <servlet>
            <servlet-name>ConfigServlet</servlet-name>
            <servlet-class>com.example.ConfigServlet</servlet-class>
            <init-param>
                <param-name>configParam</param-name>
                <param-value>configValue</param-value>
            </init-param>
        </servlet>
        <servlet-mapping>
            <servlet-name>ConfigServlet</servlet-name>
            <url-pattern>/config</url-pattern>
        </servlet-mapping>
    </web-app>

Example
2.  Servlet Implementation :
    java
    package com.example;

    import java.io.IOException;
    import javax.servlet.ServletConfig;
    import javax.servlet.Servlet Context;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    @WebServlet("/config")
    public class ConfigServlet extends HttpServlet {

        private String configParam;

        @Override
        public void init(Servlet Config config) throws ServletException {
            super.init(config);
            configParam = config.getInitParameter("configParam");
        }

        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            ServletContext context = getServlet-Context();

            // Accessing context-wide initialization parameter
            String globalParam = context.getInitParameter("globalParam");

            // Setting and getting an attribute
            context.setAttribute("sharedData", "This is shared data");
            String sharedData = (String) context.getAttribute("sharedData");

            // Sending response
            response.setContentType("text/html");
            response.getWriter().println("<h1>Config Parameter: " + configParam + "</h1>");
            response.getWriter().println("<h1>Global Parameter: " + globalParam + "</h1>");
            response.getWriter().println("<h1>Shared Data: " + sharedData + "</h1>");
        }
    }
    

Detailed Breakdown

1.  Initialization Parameters

  • ServletConfig : In the web.xml file, a servlet-specific initialization parameter configParam with the value configValue is defined for the ConfigServlet.
  • Servlet Context : A context-wide initialization parameter globalParam with the value globalValue is defined.

2.  Accessing Initialization Parameters

  • Servlet Config : In the init method of ConfigServlet, the ServletConfig object is used to retrieve the value of configParam.
  • ServletContext : In the doGet method, the Servlet-Context object is used to retrieve the value of globalParam.

3.  Attribute Management

   Servlet Context : The servlet sets an attribute sharedData in the Servlet Context and then retrieves it to send it as part of the response.

4.  Logging

   Although not demonstrated in the example, the Servlet-Context can log messages using the log method.

Homepage

Readmore