![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e1036. Getting and Setting Initialization Parameters for a ServletThe servlet container supports the ability to store startup and configuration information for a servlet. After the container instantiates the servlet, it makes this information available to the servlet instance. This example demonstrates a servlet that retrieves some initialization parameters in itsinit() method:
// See also e1035 The Quintessential Servlet // This method is called by the servlet container just before this servlet // is put into service. public void init() throws ServletException { getServletContext().log("getinit init"); // Get the value of an initialization parameter String value = getServletConfig().getInitParameter("param1"); // Get all available intialization parameters java.util.Enumeration enum = getServletConfig().getInitParameterNames(); for (; enum.hasMoreElements(); ) { // Get the name of the init parameter String name = (String)enum.nextElement(); // Get the value of the init parameter value = getServletConfig().getInitParameter(name); } // The int parameters can also be retrieved using the servlet context value = getServletContext().getInitParameter("param1"); }The initialization parameters for the servlet are specified in the deployment descriptor (i.e., web.xml file). Here is an example of a deployment descriptor that specifies two initialization parameters: <web-app> <servlet> <servlet-name>MyServletName</servlet-name> <servlet-class>com.mycompany.MyServlet</servlet-class> <init-param> <param-name> param1 </param-name> <param-value> value1 </param-value> </init-param> <init-param> <param-name> param2 </param-name> <param-value> value2 </param-value> </init-param> ... </servlet> ... </web-app>Note that the leading and trailing space around the parameter value is trimmed.
e1037. Returning an Image in a Servlet e1038. Saving Data in a Servlet e1039. Logging a Message in a Servlet © 2002 Addison-Wesley. |