ServletConfig Interface

Introduction

  • A web container is responsible for creating ServletConfig object for each servlet.
  • The ServletConfig object passes the information to a Servlet during initialization.
  • The advantage of ServletConfig is that it eliminates the need to edit the servlet file if the information is modified from the web.xml file.

ServletConfig Interface Methods

MethodsDescription
getInitParameter(java.lang.String name)Returns a String containing the value of the name initialization parameter
getInitParameterNames( )Returns the name of the servlet initialization parameters.
getServletContext( )Returns the reference of the ServletContext.
getServletName( )Returns the name of the servlet instance.

Example : Illustrating the use of ServletConfig Interface

//web.xml

<web-app>
     <servlet>
         <servlet-name>test</servlet-name>
         <servlet-class>MyServlet</servlet-class>
         <init-param>
              <param-name>email</param-name>
              <param-value>abc@yahoo.com</param-value>
         </init-param>
     </servlet>
     <servlet-mapping>
         <servlet-name>test</servlet-name>
         <url-pattern>/test</url-pattern>
     </servlet-mapping>
</web-app>

//ServletDemo.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletDemo extends HttpServlet
{
      protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
      {
           response.setContentType("text/html");
           PrintWriter pw = response.getWriter();
           ServletConfig sc = getServletConfig();
           try
           {
                pw.println(sc.getInitParameter(email));
           }
           finally
           {
                pw.close();
                sc.close();
           }
      }
}