Home/Tutorials/Java Servlet/ServletConfig interface
Java Servlet2 min read

ServletConfig interface

In this tutorial we will get an Introduction to ServletConfig interface and how it works.

Introduction to ServletConfig interface

When the Web Container initializes a servlet, it creates a ServletConfig object for the servlet. ServletConfig object is used to pass information to a servlet during initialization by getting configuration information from web.xml(Deployment Descriptor).


Methods of ServletConfig

  • String getInitParameter(String name): returns a String value initialized parameter, or NULL if the parameter does not exist.
  • Enumeration getInitParameterNames(): returns the names of the servlet's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the servlet has no initialization parameters.
  • ServletContext getServletContext(): returns a reference to the ServletContext
  • String getServletName(): returns the name of the servlet instance

How to Initialize a Servlet inside web.xml

In the Deployment Descriptor(web.xml) file,

how to initialize a servlet using deployment descriptor

Or, Inside the Servlet class, using following code,


 ServletConfig sc = getServletConfig();
 out.println(sc.getInitParameter("email"));

Example demonstrating usage of ServletConfig

web.xml

<web-app...>
   <servlet>
      <servlet-name>check</servlet-name>
      <servlet-class>MyServlet</servlet-class>
      <init-param>
            <param-name>email</param-name>
            <param-value>[email protected]</param-value>
      </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>check</servlet-name>
        <url-pattern>/check</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
     </welcome-file-list>   
</web-app>

MyServlet class :

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

public class MyServlet extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
       
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ServletConfig sc = getServletConfig();
        out.println(sc.getInitParameter("email")); 
    }
}


INTERACTIVE SIMULATION CHALLENGE+250 XP
Workbench Verification

Ready to test "ServletConfig interface" in production?

See how Java Servlet algorithms and server loops perform under 100k req/s traffic spikes.

Simulator: SysDesign Ops Simulator