10.7. Loading XML Data into Your Application

Problem

You want an easy way to load XML data into application-scoped objects when your application starts up.

Solution

Use the DigestingPlugIn provided in Struts 1.2.

First, decide on the class that will represent the data. If the data will be used in drop-down lists, a convenient option is to use use the Struts-provided LabelValueBean (org.apache.struts.util.LabelValueBean). Next, create the XML-formatted datafile. The struts-example includes a file called server-types.xml that represents types of electronic mail server types:

<lv-beans>
    <lv-bean label="IMAP Protocol" value="imap" />
    <lv-bean label="POP3 Protocol" value="pop3" />
</lv-beans>

Create the rules file that controls how the Digester will parse the data into objects. The lvb-digester-rules.xml file shown in Example 10-20, from the struts-example, specifies the parsing rules to create an ArrayList of LabelValueBeans from the server-types.xml file.

Example 10-20. Label value bean Digester rules

<digester-rules>
    <object-create-rule pattern="lv-beans" 
                      classname="java.util.ArrayList"/>
    <pattern value="lv-beans/lv-bean">
        <object-create-rule classname="org.apache.struts.util.
        LabelValueBean" />
        <set-properties-rule />
        <set-next-rule methodname="add" />
    </pattern>
</digester-rules>

Finally, add a plug-in declaration to your struts-config.xml for each file to be parsed and loaded:

<plug-in className="org.apache.struts.plugins.DigestingPlugIn"> <set-property property="key" value="serverTypes"/> ...

Get Jakarta Struts Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.