Servlet Tutorials

ServletConfig Interface
Previous Home Next
adplus-dvertising

Here we can be an object of ServletConfig is created by the web container,which is used to get configuration information from web.xml file.

ServletConfig the configuration information is modified from the web.xml file,change the servlet can be performed. So it is easier to manage the web application if any specific content is modified from time to time.

Advantage

The core advantage of ServletConfig is that you don't need to edit the servlet file if information is modified from the web.xml file.

ServletConfig interface Methods as follows :

  1. public String getInitParameter(String name):It is returns the parameter value for the specified parameter name.
  2. public Enumeration getInitParameterNames():It is returns an enumeration of all the initialization parameter names.
  3. public String getServletName():It is returns the name of the servlet.
  4. public ServletContext getServletContext():It is returns an object of ServletContext.

How to get the object of ServletConfig

getServletConfig() method of Servlet interface returns the object of ServletConfig.

Syntax used
public ServletConfig getServletConfig();
Example of getServletConfig() method
ServletConfig config=getServletConfig();
//Now we can call the methods of ServletConfig interface
Syntax of initialization parameter for a servlet

The init-param sub-element of servlet is used to specify the initialization parameter for a servlet.

<web-app>
  <servlet>
    ......
    <init-param>
      <param-name>parametername</param-name>
      <param-value>parametervalue</param-value>
    </init-param>
    ......
  </servlet>
</web-app>
Example of ServletConfig to get initialization parameter

Getting the one initialization parameter from the web.xml file and printing this information in the servlet.

DemoServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
	response.setContentType("text/html");
	PrintWriter out = response.getWriter();
	ServletConfig config=getServletConfig();
	String driver=config.getInitParameter("driver");
	out.print("Driver is: "+driver);	
	out.close();
	}
}
web.xml
<web-app>
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
<init-param>
<param-name>driver</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>
Previous Home Next