ServletConfig in Servlet

In this article we will see about ServletConfig Interface and how it works. The config object is created by the web container based on the initialization parameters specified in the deployment descriptor. It is used to send information to a servlet during initialization.

Now let see the methods of ServletContext interface, which are listed the following table:

String getInitparameter(String Name)It returns the Servlet initialization parameter of the given name and if the requested parameter is not available then it returns null.
Enumeration getInitparameter Names( )It returns names of all Servlet initialization parameters defined in web.xml file.
String getServletName()Returns the servlet name as defined in the deployment descriptor .
ServletContext getServletContext()Returns the ServletContext object reference.

ServletConfig Example

Let us try out simple example to understand the working of the ServletConfig. Create a class named ServletconfigExample. This class shall create an object of ServletConfig and fetch the init-param from the deployment descriptor and print on the screen.

Listing 1: ServletconfigExample



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 ServletconfigExample extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		PrintWriter out = response.getWriter();

		ServletConfig config = getServletConfig();
		String S1 = config.getInitParameter("websitename");
		out.print("I'm : " + S1 + "website!!!!");


Listing 2: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=""
	xmlns="" xmlns:web=""
	id="WebApp_ID" version="3.0">




Here we have defined the <init-param> which defines a param-name as websitename and param-value as Javabeat.

Now execute the ServletconfigExample, right click select Run>Run As and the following output appears:

Previous Tutorial : sendRedirect in Servlet  || Next Tutorial : Difference Between JSP and Servlet

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!