What is ServletConfig in Java J2EE application

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 {
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();

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

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

  out.close();
 }

 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"
 xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 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>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>


 <servlet>
  <servlet-name>servletConfigTest</servlet-name>
  <servlet-class>com.ekiras.ServletConfigTest</servlet-class>

  <init-param>
   <param-name>name</param-name>
   <param-value>ekiras</param-value>
  </init-param>

  <init-param>
   <param-name>blog</param-name>
   <param-value>http://ekiras.blogspot.com</param-value>
  </init-param>

 </servlet>

 <servlet-mapping>
  <servlet-name>servletConfigTest</servlet-name>
  <url-pattern>/test</url-pattern>
 </servlet-mapping>



</web-app>
The above will give the following output when run in a servlet container like tomcat with url /test
name=ekiras
blog=http://ekiras.blogspot.com

No comments:

Powered by Blogger.