Friday, 10 July 2015

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.javatpoint.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.javatpoint.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.javatpoint.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>  
  4. </pre></div>  
  5.   
  6. <h3 class="h3">2) Create the action class</h3>  
  7. <p>It is the simple action class containing execute method only.</p>  
  8. <strong>Welcome.java</strong>  
  9. <div class="codeblock"><textarea name="code" class="java" >  
  10. package com.javatpoint;  
  11.   
  12. public class Welcome {  
  13. public String execute(){  
  14.     return "success";  
  15. }  
  16. }  

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>