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="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5" xmlns="http://java.sun.com/xml/ns/javaee">
  <description>sample web.xml file for task flow</description>
  <display-name>MyApp.jws</display-name>
  <context-param>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
  </context-param>


<context-param>
    <param-name>myParam1</param-name>
    <param-value>user@domain.com</param-value>
  </context-param>
<context-param>
    <param-name>myParam2</param-name>
    <param-value>xyz</param-value>
  </context-param>

...

<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>


...

</web-app>


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