I'm trying to map my struts actions using wildcards. Before, I used UrlRewrite Filter by Tuckey. But this thread changed my mind.
So here's my problem: My URL's look like the following:
- www.example.com/promoties/category-123
- www.example.com/promoties/category-123/subcategory-456
In these examples, the words "category" and "subcategory" are dummy data. Used to make the URL more relevant for search engines.
Now i'd like to ignore this dummy data, as I'm just interested in the (last) ID. In the first case 123 in the last case 456.
How would I go about doing this in Struts2?
I've tried the following without success:
<package name="promoties" namespace="/promoties" extends="struts-default">
<action name="([0-9a-zA-Z\-_]+)-{id:([0-9]+)}$" class="CategoryAction">
<result type="tiles">categorydetail</result>
</action>
</package>
Using following options in my struts config:
<constant name="struts.enable.SlashesInActionNames" value="true"/>
<constant name="struts.mapper.alwaysSelectFullNamespace" value="false"/>
<constant name="struts.patternMatcher" value="regex" />
Has anyone tried this before? How would I go about doing this in Struts2?
One way is to use simple wild card mapping and regulate the validation of the id component to struts2 validation. Here is an example which has been tested, but without validation.
struts.xml you'll see an action defined for category-* and category-*/subcategory-* in the second we'll just keep the second wild card.
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<constant name="struts.ognl.allowStaticMethodAccess" value="true"/>
<constant name="struts.enable.SlashesInActionNames" value="true"/>
<constant name="struts.mapper.alwaysSelectFullNamespace" value="false"/>
<package namespace="" name="default" extends="struts-default">
<action name="category-*" class="test.TestBean">
<param name="id">{1}</param>
<result>/WEB-INF/content/test/results.jsp</result>
</action>
<action name="category-*/subcategory-*" class="test.TestBean">
<param name="id">{2}</param>
<result>/WEB-INF/content/test/results.jsp</result>
</action>
</package>
</struts>
test.TestBean here I used a String but in your case you'll change this to int or Integer. You'll want to validate that we did get an integer using validation xml or simply implementing com.opensymphony.xwork2.Validateable.
package test;
import com.opensymphony.xwork2.ActionSupport;
public class TestBean extends ActionSupport{
//public to avoid get/set to make example shorter
public String id;
}
/WEB-INF/content/test/results.jsp
<%@taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
<h1>Wild Card Value</h1>
id: <s:property value="id"/>
</body>
</html>
Example 1
The url: example.com/category-helloBart produces...
Wild Card Value
id: helloBart
Example 2
The url: example.com/category-helloBart/subcategory-123 produces...
Wild Card Value
id: 123