Points To Remember
  • Each Servlet has its own ServletConfig object.
  • ServletConfig is defined in web.xml
  • ServletConfig is a way of giving init parameters to a servlet during initialization. 
  • ServletConfig is a predefined interface.
  • ServeltConfig object is created by the container when a servlet is initialized and this object remains with the servlet throughout the life cycle of the servlet.
Example : How to get ServletConfig Object in a Servlet.
Lets take an example where we will add a few init params in the servlet config and get the config object from the servlet config object within the servlet.
package com.ekiras;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletConfigTest extends HttpServlet {
private static final long serialVersionUID = 1L;

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

ServletConfig config = getServletConfig();
Enumeration<String> e = config.getInitParameterNames();

String param = "";
while (e.hasMoreElements()) {
param = e.nextElement();
out.print(" = " + config.getInitParameter(param) +"<br/>");


protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {



The following is the web.xml with the servlet mapping and init params for servlet.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>Servlet Config Test</display-name>






The above will give the following output when run in a servlet container like tomcat with url /test