July 5, 2011

Breaking a large struts.xml into multiple smaller files

A large struts.xml can be broken in several smaller XML files - this makes the struts configuration modular and much convenient to work with in a team environment.

The <include> element can be used to apply the divide-and-conquer approach to Struts configuration files.

1) Modify the struts.xml file from this example to the following,

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
   <include file="another-struts.xml" />
</struts>

Another number of modular, external XML files can be included in the struts.xml - they should be present anywhere in the classpath of the web application.

2) Add a new configuration file in the default package of the src folder of the web application, named another-struts.xml - add the following configuration in this file,

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
   <constant name="struts.devMode" value="true" />

   <package name="myPackage" extends="struts-default">

      <action name="Name">
     <result>/NameCollector.jsp</result>
      </action>
  
      <action name="HelloWorld" class="info.icontraining.struts2.HelloWorld">
  <result>/Hello.jsp</result>
      </action>
     </package>
</struts>

Each included file such as another-struts.xml must be in the same format as the original struts.xml including the DOCTYPE at the top.

3) Test the code in the example with the same URL as the example referred to in step-1,

http://localhost:8080/WebAppName/Name.action

NOTE: Also refer the following URL - http://www.mkyong.com/struts2/struts-2-include-multiple-struts-configuration-files/

No comments:

Post a Comment