ServletConfig Interface in Servlet

As of now, we have seen the HttpServlet class. In this article, we will discuss the ServletConfig Interface. As we know about Interface in java so we have ServletConfig Interface in servlet.ServletConfig is created by a web container for each servlet.

What is the ServletConfig Interface?

ServletConfig is an object for the servlet. Whenever the servlet is initialized the ServletConfig passes information to it by getting information from one file called web.xml.It has an advantage like if any changes occur in web.xml we don’t need to edit the servlet file.

Advantages of ServletConfig

  • If any changes occur in the deployment descriptor (web.xml) we don’t need to change the servlet.

In order to go forward Let’s see first What is WEB.xml file?

Web.xml

Web.xml is a file inside Web-INF in your web application.it is used to define the name of the servlet and the mapping of URL pattern is done with the help of web.xml which is a deployment descriptor. In order to access java servlet from a browser, we have to tell the web container to deploy it, and what URL’s to map. This is done using a web.xml file. Following is a web.xml file

<servlet>
  <servlet-name>abc</servlet-name>
  <servlet-class>ServletRequestDemo</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>abc</servlet-name>
  <url-pattern>/abc</url-pattern>
</servlet-mapping>
  • <servlet>: This element is used to configure the servlet. In this, we give the servlet name and servlet class name.
    • <servlet-name>: In this, we provide the name of the servlet(we can give it any name).
    • <servlet-class>: In this, we provide the name of the class of our servlet.
  • <servlet-mapping>: This element is used to map the URL of the servlet.
    • <servlet-name>: In this, we provide the name of the servlet same as that of <servlet> element.
    • <url-pattern>: In this, we provide a mapping of a URL pattern. (in above ex./abc sent to servlet).There are multiple possible ways to write a URL pattern.
        • /abc
        • /abc.do
      • /abc*(* is a wild card which means any text).

Methods in ServletConfig

  • public String getInitParameter(String name): This method returns the value of the parameter for the parameter value.
    • Parameter
      • name: It is a string that specifies the name of the initialization parameter.
  • public Enumeration getInitParameterNames():This method returns the Enumeration of all initialization parameters.
  • public String getServletName(): This method returns the name of the servlet.
  • public ServletContext getServletContext():This method returns the object of ServletContext.

Let’s see the Example for ServletConfig Interface

In this example, we have used the Init parameter in web.xml with parameter name and value.In Servlet it is accessed by getInitParameter() method with ServletConfig object.

Example.java

Output