Struts 2 Multiple Namespace Example

Struts 2 Multiple Namespace example. Let's see the simple example to create multiple namespace in struts 2 application.

Struts 2 Multiple Namespace Example

Struts 2 Multiple Namespace Example

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

 

  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts   
  3. Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">  
  4. <struts>  
  5.   
  6. <package name="default1" namespace="/" extends="struts-default">  
  7. <action name="hello"  class="com.hpnmaratt.Welcome">  
  8. <result>welcome.jsp</result>  
  9. </action>  
  10. </package>  
  11.   
  12. <package name="default2" namespace="/first" extends="struts-default">  
  13. <action name="hello"  class="com.hpnmaratt.Welcome">  
  14. <result>welcome.jsp</result>  
  15. </action>  
  16. </package>  
  17.   
  18. <package name="default3" namespace="/second" extends="struts-default">  
  19. <action name="hello"  class="com.hpnmaratt.Welcome">  
  20. <result>welcome.jsp</result>  
  21. </action>  
  22. </package>  
  23.   
  24. </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

 

  1. <a href="hello">root namespace</a>|  
  2. <a href="first/hello">first namespace</a>|  
  3. <a href="second/hello">second namespace</a>  

2) Create the action class

It is the simple action class containing execute method only.

Welcome.java

 

  1. package com.hpnmaratt;  
  2.   
  3. public class Welcome {  
  4. public String execute(){  
  5.     return "success";  
  6. }  
  7.  

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.

  1. <h1>Welcome to root namespace</h1>  

welcome.jsp

 

It must be located in the first directory under the root directory.

  1. <h1>Welcome to first namespace</h1>  

welcome.jsp

 

It must be located in the second directory under the root directory.

  1. <h1>Welcome to second namespace</h1>