ServletConfig
When the container initializes the servlet it makes a unique ServletConfig for it.Its main job is to give us init parameters.
The container reads the servlet init parameters from the Deployment Descriptor and gives them to the ServletConfig and then passes the ServletConfig to the servlet’s init() method.
Methods of the ServletConfig interface
The following methods can be called on the ServletConfig object:
getInitParameter(String)
This method returns a String containing the value of the named initialization parameter,Return value will be null
if the parameter does not exist.
Enumeration getInitParameterNames()
This method returns the names of the servlet’s initialization parameters as an Enumeration of string. This method will return an empty Enumeration if the servlet has no initialization parameters.
getServletContext()
This method returns a reference to the ServletContext in which the caller is executing.
getServletName()
This method returns the name of this servlet instance. Servlet name can be assigned in the web application deployment descriptor.
Initialization Parameters
In case you want to put a certain value (an email address for example) in your servlet, a better option would be to configure it in the Deployment Descriptor(web.xml) rather than hard-coding it in the servlet class.
The getInitParameter() can be called on the ServletConfig object to return the init parameter but only once init() is called.
Example for getting init parameters from ServletConfig
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.j2eereference.servlet; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class TestServletConfig extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{ response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.println("Testing ServletConfig and init parameters"); java.util.Enumeration e=getServletConfig().getInitParameterNames(); while(e.hasMoreElements()){ out.println("param name = "+e.nextElement()); } out.println("main email is "+getServletConfig().getInitParameter("adminEmail")); } } |
The web.xml file for the above servlet is shown below :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?xml version=”1.0″ encoding=”ISO-8859-1″?> <web-app xmlns=”http://java.sun.com/xml/ns/j2ee” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd” version=”2.4″> <servlet> <servlet-name>ParamTesting</servlet-name> <servlet-class>com.j2eereference.j2ee.TestServletConfig</servlet-class> <init-param> <param-name>adminEmail</param-name> <param-value>admin@209.97.166.197</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>ParamTesting</servlet-name> <url-pattern>/Tester.do</url-pattern> </servlet-mapping> </web-app> |
Leave a Reply