Wilcard mappings in Struts 2

Tags:

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.

Download war file

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:

Mappings are matched against the request in the order they appear in the framework’s configuration file. If more than one pattern matches the last one wins, so less specific patterns must appear before more specific ones. However, if the request URL can be matched against a path without any wildcards in it, no wildcard matching is performed and order is not important.

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:

While using Struts 2 it may be sensible to prevent other developers from using a URL in their code such as /index.jsp. The reason for this is so that no matter what you do with the page in the future it will always be processed through the Struts 2 framework. This can be achieved by putting your jsp pages into the WEB-INF folder in your web application which by default is inaccessable. This will force developers to use URL’s like index.action, about.action or our-address.action and therefore engage the Struts framework.

Comments:

Remove namespace then it works fine

Post a Comment:

HTML Syntax: Allowed