Struts 2 comes with “include file” feature to include multiple Struts configuration files into a single unit.
Single Struts configuration file
Let’s see a bad Struts 2 configuration example.
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
</package>
<package name="audit" namespace="/audit" extends="struts-default">
<action name="WelcomeAudit">
<result>pages/welcome_audit.jsp</result>
</action>
</package>
<package name="user" namespace="/user" extends="struts-default">
<action name="WelcomeUser">
<result>pages/welcome_user.jsp</result>
</action>
</package>
</struts>
In the above Struts configuration file, it group all the “user
” and “audit
” settings in a single file, which is not recommend and MUST BE AVOID. You should break up this struts.xml
file into more smaller module related pieces.
Do not think this is a case study, it did happened in real life. I seen many Struts 1 or 2 developers just group everything in a single Struts configuration file. In fact, many are still don’t aware of the Struts’s include file feature.
Multiple Struts configuration files
In Struts 2, you should always assign each module a struts configuration file. In this case, you can create three files :
struts-audit.xml
– Put all audit module settings here.struts-user.xml
– Put all user modules settings here.struts.xml
– Put default settings and include thestruts-audit.xml
andstruts-user.xml
.
struts-audit.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="audit" namespace="/audit" extends="struts-default">
<action name="WelcomeAudit">
<result>pages/welcome_audit.jsp</result>
</action>
</package>
</struts>
struts-user.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="user" namespace="/user" extends="struts-default">
<action name="WelcomeUser">
<result>pages/welcome_user.jsp</result>
</action>
</package>
</struts>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
</package>
<include file="user/struts-user.xml"></include>
<include file="audit/struts-audit.xml"></include>
</struts>
See how the folder structure look like