Saturday, January 9, 2010

Struts 2 Namespaces

Here are a few things that I learnt about struts 2 namespaces during my silly experiments.


  1. The namespace attribute of element in struts.xml is an optional attribute. The default namespace is "" . i.e. an empty string.

  2. The value of your namespace must always begin with a "/".

  3. Namespaces are used to group together a set of actions.

  4. An action with the same name can exist in several namespaces. The action that will be invoked depends upon the namespace in which it is called.

According to the struts 2 documentation, struts 2 tags are meant to be namespace aware. i.e. you should not need to append the namespace name in the url's and links in on a jsp page when creating links. However, it does not seem to be working for me. So, i use the namespace attribute whenever necessary.

However, if an action with the same name exists in multiple namespaces then the action in the default namespace is called if no namespace is specified in the link.

An important point to note is that when you declare a package with a namespace, all the results that you configure for an action usuing the result tag are assumed to be relative to that namespace if they are not preceded by a /.

For example suppose you have the following configuration in struts.xml such that the same action name is present in two packages but the namespaces are different. Let us assume that the name of your web application root is 'struts2app'



            
                success.jsp
            
        
 
            
                failure.jsp
            
        


In your jsp page, you can access action1 in namespace1 by writing the following code




Click Me To Test Namespace


Struts will look for the page success.jsp in struts2app/namespace1/success.jsp

However, if your success.jsp is exists direcly under the root directory, the you need to specify the result configuration as follows.




/success.jsp




The leading "/" indicates that the page is located at the web application root.
          
In this case, struts will try to find the page success.jsp in struts2app/success.jsp

That takes care of the bare basics of using namsepaces in struts 2.

Signing Off
Ryan

3 comments:

Unknown said...

Thanks, your article on namespaces was very usefull for me.Keep writing.

Unknown said...

Really just now I got clear my namespace concept. Thanks !

Unknown said...

Really just now I got clear my namespace concept. Thanks !