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();

Example demonstrating usage of ServletConfig



MyServlet class :

import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        ServletConfig sc=getServletConfig();