我正在尝试使用通配符映射我的 Struts 操作。
之前,我使用了 Tuckey 的 UrlRewrite Filter。但是 this question 改变了我的想法。
所以这是我的问题:我的 URL 如下所示:
www.example.com/promoties/category-123
www.example.com/promoties/category-123/subcategory-456
在这些示例中,单词 category
和 subcategory
是虚拟数据,用于使 URL 与搜索引擎更相关。
现在我想忽略这个虚拟数据,因为我只对(最后一个)ID 感兴趣。第一种情况 123
最后一种情况 456
.
我尝试了以下但没有成功:
<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>
在我的 struts.xml
中使用以下选项:
<constant name="struts.enable.SlashesInActionNames" value="true"/>
<constant name="struts.mapper.alwaysSelectFullNamespace" value="false"/>
<constant name="struts.patternMatcher" value="regex" />
有没有人试过这个?我将如何在 Struts2 中执行此操作?
最佳答案
一种方法是使用简单的通配符映射并将 id 组件的验证规范为 struts2 验证。这是一个已经过测试但未经验证的示例。
struts.xml 您将在第二个时间段中看到为 category-* 和 category-*/subcategory-* 定义的操作将只保留第二张通配符。
<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 此处我使用了字符串,但在您的情况下,您需要将其更改为 int 或 Integer。您需要使用验证 xml 或简单地实现 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>
示例 1 url: example.com/category-helloBart 产生...
通配符值
编号:你好
示例 2 url: example.com/category-helloBart/subcategory-123 产生...
通配符值
编号:123
关于url-rewriting - Struts 2 中带有虚拟数据的通配符操作映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5484392/