Struts 2 Multiple Namespace Example


Struts 2 namespace provides a functionality to resolve the conflict between same actions names located at different modules. We can define the multiple namespaces in core configuration file (struts.xml) of package element.

Have loop of URL, that sends the request to Struts 2 application.

Struts 2 Multiple Namespace Example

Namespace Configuration

Define the multiple packages inside the struts.xml identified by different namespaces.

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>
	<constant name="struts.devMode" value="true" />
	<package name="default" namespace="/" extends="struts-default">
		<action name="welcome">
			<result>/index.jsp</result>
		</action>
	</package>

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

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

View Components

In my demo, I have created two namespaces which redirect you on the respective results.

index.jsp is the default page mapped with root (/) namespace and action="welcome"

<html>
<head>
<title>Namespace</title>
</head>
<body>
	<h1>Struts 2 Multiple Namespace Configuration Example</h1>
	<p>Click Me</p>
	<ol>
		<li><a href="welcome">Default</a></li>
		<li><a href="first/WelcomeFirst">First</a></li>
		<li><a href="second/WelcomeSecond">Second</a></li>
	</ol>
</body>
</html>

first.jsp is the first page and it is mapped with first namespace and action="WelcomeFirst"

<html>
<head>
<title>First Namespace</title>
</head>
<body>
	<h2>Welcome to First Namespace</h2>
</body>
</html>

second.jsp is the second page and it is mapped with second namespace and action="WelcomeSecond"

<html>
<head>
<title>Second Namespace</title>
</head>
<body>
	<h2>Welcome to Second Namespace</h2>
</body>
</html>

Project Structure in Eclipse

Struts 2 Multiple Namespace Example

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.