Struts2 Multiple Configuration Files

 

In Struts 2, we can include multiple struts config files into a single file using the <include .../> element, This is useful when we have a project which is divided into different business domains (divide and conquer).

In this example we will create two struts config files struts-customer.xml and struts-supplier.xml and include them into the struts.xml file using the <include .../> tag.

 

 1. Project structure

Struts2 Multiple Configuration Files 0
 

2. struts-customer.xml

Put inside all settings related to the “customer” domain.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>

	<package name="customer" namespace="/customer" extends="struts-default">
		<action name="welcome">
			<result>/customer/welcome-customer.jsp</result>
		</action>
	</package>

</struts>

 

3. struts-supplier.xml

Put inside all settings related to the “supplier” domain.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>

	<package name="supplier" namespace="/supplier" extends="struts-default">
		<action name="welcome">
			<result>/supplier/welcome-supplier.jsp</result>
		</action>
	</package>

</struts>

 

4. struts.xml

Define the default settings then import the two config files  struts-customer.xml and struts-supplier.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>

	<package name="default" namespace="/" extends="struts-default">
		<action name="welcome">
			<result>/welcome.jsp</result>
		</action>
	</package>

	<include file="customer/struts-customer.xml" />
	<include file="supplier/struts-supplier.xml" />

</struts>

 

 5. JSP views

welcome.jsp : default home page

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
	<s:form action="welcome">
		<h2> Hello World! </h2>
	</s:form>
</body>
</html>

welcome-customer.jsp : “customer” home page

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
	<s:form action="customer">
		<h2> Hello Customer! </h2>
	</s:form>
</body>
</html>

welcome-supplier.jsp : “supplier” home page

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
	<s:form action="supplier">
		<h2> Hello Supplier! </h2>
	</s:form>
</body>
</html>

 

6. Test It

Using the default config :

Struts2 Multiple Configuration Files

 

Using the “customer” module config :

Struts2 Multiple Configuration Files 1

 

Using the “supplier” module config :

Struts2 Multiple Configuration Files 2

 

Download source code