| This Chapter | |
| - | Chapter 14: The Config Object |
| - | Using the web.xml File or Properties Files |
| - | The Config Object |
| - | Summary |
Properties files are a popular choice for Java programmers to store configuration settings. Inside a properties file you have key/value pairs. Once you know the name and the location of the file, reading it is straightforward.
In Web applications, the deployment descriptor (the web.xml file) provides a similar function, and is more convenient to use than a properties file because you don’t need to worry about instantiating a file reader. You normally store configuration settings in context-param elements, each of which represents a key/value pair. For example, here is the context-param element that stores the value of dataPattern.
<context-param>
<param-name>datePattern</param-name>
<param-value>MM/dd/yyyy</param-value>
</context-param>
The values of context-param elements are loaded automatically into the ServletContext object. Since the ServletContext object is accessible from any Struts action object (through the getServlet().getContext() method of the org.apache.struts.action.Action class) as well as from any JSP through the EL or JSTL and other custom tags, this seems a good place to store shareable values.
For instance, you can define a date pattern as a context parameter in the web.xml file by using the following context-param element.
<context-param> <param-name>datePattern</param-name> <param-value>MM/dd/yyyy</param-value> </context-param> :
To read the value of datePattern and use it to format a date, use the formatDate tag in JSTL.
<jsp:useBean id="today" class="java.util.Date"/>
<f:formatDate value="${today}" pattern="${initParam.datePattern}"/>
Unfortunately, the values in the deployment descriptor are not visible from other business objects. This leads us to an alternative approach to sharing values across the application, as discussed in the following section.