Wilcard mappings in Struts 2
Problem summary
To be able to uses only Struts 2 anchor tags (<s:a> - hyperlink) which point to a URL ending in .action without having to have an action class for every jsp page.
This is almost identical to the Namespaces in struts 2 tutorial I did earlier but this time we remove the Java classes and replace them with 3 lines in struts.xml (for each namespace) and a single java class.
If we take a look at a struts.xml <package> node that uses a wildcard mapping we see:
<package name="root" extends="struts-default" namespace="/">
<action name="*" class="struts2you.examplelogin.BaseActionSupport">
<result name="success">{1}.jsp</result>
</action>
</package>
The <action> node in this case is not the same as in Struts 1 as the <action name=”*”> is a wild card mapping and hence has a *. This means that any Struts 2 action that is hit in the namespace /, such as /index.action, /about.action or /our-address.action will match this action. The result is that the <action> node will execute the success result and map to /index.jsp, /about.jsp or /our-address.jsp - the {1} means that anything before the .action is put in place of it. So, if you hit /index.action the index is stripped from the URL and is put in place of the {1} resulting in index.jsp with the namespace / and so would redirect to /index.jsp.
Taken from the Struts 2 documentation on wildcard mappings:
This means that the wildcard mapping should go at the top of the struts.xml configuration file.
You may be wondering what is in the struts2you.examplelogin.BaseActionSupport class:
package struts2you.examplelogin;
import com.opensymphony.xwork2.ActionSupport;
public class BaseActionSupport extends ActionSupport {
}
The answer if almost nothing, it has two purposes:
- It solves our original problem by acting as a simple and invisible ‘pass through’ so that all our URL references can be processed through Struts 2 without you having to have a matching
node in the struts.xml file. This is good when the jsp does not have any Struts related processing and working this way means that, should you decide to change the page in the future and make it ‘Struts aware’, less work will be required in changing all the URL’s that point to that page. Using the above method you can always hit index.action rather then being forced to hit index.jsp as you would have to do if you did not have the wildcard mapping; - It allows all other classes to extend it (and hence extend ActionSupport) and works as a placeholder common to all your classes where you can put shared code.
18.02.2009 12:00 - Posted by doahh - Comments: 1 - Java

Comments:
Remove namespace then it works fine
16.02.2010 01:48 - Posted by Deepak - Permalink