Today, Budi walks us through a refresher and brief overview of server JSP programming. Today's portion covers Servlet technologies, including servlets and Tomcat. This excerpt comes from chapter one of JavaServer Faces Programming, by Budi Kurniawan (McGraw-Hill/Osborne, ISBN 0-07-222983-7, 2004).
To retrieve a context parameter name and value defined in the deployment descriptor, you first need to obtain the ServletContext object using the getServletContext method of the ServletConfig object. You then call two methods of the ServletContext interface:
The getInitParameterNames method, which does not take an argument and returns a java.util.Enumeration containing all the context parameter names.
The getInitParameter method, which takes a String argument containing the parameter name and returns a String containing the value of the parameter.
The code in Listing 3 is an init method of a servlet called ContextParamDemoServlet. It loops through the Enumeration object called parameters, which is returned from the getInitParameterNames method. For each parameter, it outputs the parameter name and value. The parameter value is retrieved using the getInitParameter method.
Listing 3Retrieving Context Parameters
public void init(ServletConfig config) throws ServletException { ServletContext servletContext = servletConfig.getServletContext(); Enumeration parameters = servletContext.getInitParameterNames(); while (parameters.hasMoreElements()) { String parameter = (String) parameters.nextElement(); System.out.println("Parameter name : " + parameter); System.out.println("Parameter value : " + config.getInitParameter(parameter)); } }
The output of the code in the console is as follows:
Parameter name : userName Parameter value : budi Parameter name : password Parameter value : secret
Remember: This is part one of the first chapter of JavaServer Faces Programming, by Budi Kurniawan (McGraw-Hill/Osborne, ISBN 0-07-222983). Stay tuned for part 2 of "Overviews of Java Web Technologies," where we learn about JSP, JavaBeans, and Model 2. Buy this book!