We can define multiple namespaces in struts.xml file by the namespace attribute of package element. As we know, default namespace is / (root).
Let's see the simple example to define multiple namespaces in struts.xml file.
Define multiple namespaces in struts.xml
This struts.xml file contains three packages with different names and namespaces.
struts.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC "-
- Configuration 2.1
- <struts>
-
- <package name="default1" namespace="/" extends="struts-default">
- <action name="hello" class="com.javatpoint.Welcome">
- <result>welcome.jsp</result>
- </action>
- </package>
-
- <package name="default2" namespace="/first" extends="struts-default">
- <action name="hello" class="com.javatpoint.Welcome">
- <result>welcome.jsp</result>
- </action>
- </package>
-
- <package name="default3" namespace="/second" extends="struts-default">
- <action name="hello" class="com.javatpoint.Welcome">
- <result>welcome.jsp</result>
- </action>
- </package>
-
- </struts>
Other required resources
We need some other required files to understand the full example of multiple namespaces.
- index.jsp
- action class (Welcome.java)
- 3 view components
1) Create index.jsp
This jsp page provides three links.
index.jsp
- <a href="hello">root namespace</a>|
- <a href="first/hello">first namespace</a>|
- <a href="second/hello">second namespace</a>
- </pre></div>
-
- <h3 class="h3">2) Create the action class</h3>
- <p>It is the simple action class containing execute method only.</p>
- <strong>Welcome.java</strong>
- <div class="codeblock"><textarea name="code" class="java" >
- package com.javatpoint;
-
- public class Welcome {
- public String execute(){
- return "success";
- }
- }
3) 3 view components
Here name of all the 3 view components are same but there location are different.
welcome.jsp
It must be located in the root directory.
- <h1>Welcome to root namespace</h1>
welcome.jsp
It must be located in the first directory under the root directory.
- <h1>Welcome to first namespace</h1>
welcome.jsp
It must be located in the second directory under the root directory.
- <h1>Welcome to second namespace</h1>