Monday, November 7, 2011

How to: storing configuration parameters in web.xml file

Sometimes we need store application wide settings of our web application in configuration files or database. Of course one can also hardcode these parameters, but it isn't best way if we need to construct flexible, easy to maintain software.
There exists also one more, elegant and easy way to store application wide parameters: storing params in web.xml file. As you must know the web.xml file provides configuration and deployment information for the Web components that comprise a Web application. The web.xml file resides in the WEB-INF directory under the context of the hierarchy of directories that exist for a Web application. For example, if the application is myApp.war, then the web.xml file is placed in the myApp.war/WEB-INF directory.

We can store our params as shown bellow:

<?xml version = '1.0' encoding = 'UTF-8'?>
<web-app xmlns:xsi=""
         version="2.5" xmlns="">
  <description>sample web.xml file for task flow</description>



    <servlet-name>Faces Servlet</servlet-name>



When we need access stored params in web application code, it can be done very easy:

String ldapUser = getServletContext().getInitParameter("myParam1");
String ldapPassword = getServletContext().getInitParameter("myParam2");

In JSF backing bean it looks simillar, by example:

ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
String ldapUser = context.getInitParameter("myParam1");
String ldapPassword = context.getInitParameter("myParam2"); 

No comments:

Post a Comment