使用 OGNL 在 Struts 2 中创建具有 2 个动作参数的动态 URL [英] Creating dynamic URL with 2 action parameters in Struts 2 using OGNL
问题描述
如果我有一个 url:www.myurl.com/books
并且希望能够创建新的
过滤作者和年份:www.myurl.com/books/Sartre/1942
通过将 Sartre
和 1942
作为参数传递给 action 类,它将呈现书籍页面适当的结果.如何在 Struts2 中做到这一点?
If I have a url: www.myurl.com/books
and want to be able to create new <s:url>
filtering on author and year: www.myurl.com/books/Sartre/1942
by passing Sartre
and 1942
as parameters to the action class which will render the books page with the appropriate results. How to do this in Struts2?
我有后端逻辑,所以如果:
I have the backend logic in place so it would be great if:
- 我可以重用与永久链接相同的 jsp 和 action 类
www.myurl.com/books
使用. - 显示动态呈现的 URL
www.myurl.com/books/Sartre/1942
即使在获取请求加载页面之后,在地址栏中(不是www.myurl.com/books
,即).
- I could reuse the same jsp and action class that the permalink
www.myurl.com/books
uses. - Show the dynamically rendered URL
www.myurl.com/books/Sartre/1942
in the address bar even after the get request has loaded the page (notwww.myurl.com/books
, that is).
推荐答案
您需要高级通配符映射
.
来自文档:Struts2 的高级通配符映射:
高级通配符
从2.1.9+开始可以在action中定义正则表达式名称.要使用这种形式的通配符,以下常量必须是设置:
From 2.1.9+ regular expressions can be defined defined in the action name. To use this form of wild card, the following constants must be set:
<constant name="struts.enable.SlashesInActionNames" value="true"/>
<constant name="struts.mapper.alwaysSelectFullNamespace" value="false"/>
<constant name="struts.patternMatcher" value="regex" />
正则表达式可以有两种形式,最简单的一种是{FIELD_NAME}
,在这种情况下,带有 FIELD_NAME
的字段在action 将填充匹配的文本,例如:
The regular expressions can be in two forms, the simplest one is
{FIELD_NAME}
, in which case the field with the FIELD_NAME
in the
action will be populated with the matched text, for example:
<package name="books" extends="struts-default" namespace="/">
<action name="/{type}/content/{title}" class="example.BookAction">
<result>/books/content.jsp</result>
</action>
</package>
在这个例子中,如果 url /fiction/content/Frankenstein
是请求,BookAction 的字段type
"将设置为fiction
",并且字段title
"将设置为Frankenstein
".
In this example, if the url /fiction/content/Frankenstein
is
requested, BookAction's field "type
" will be set to "fiction
", and the
field "title
" will be set to "Frankenstein
".
如果使用 Struts2-Convention-Plugin,您的示例将是:
If using Struts2-Convention-Plugin, your example would be:
@Action(value="/books/{author}/{year}")
public class Books extends ActionSupport {
private String author;
private Integer year;
/* ...GETTERS AND SETTERS HERE... */
public String execute(){
/* ...LOAD DATA HERE... */
if (noDataFound)
return NONE;
return SUCCESS
}
}
如果您需要在 prepare()
方法中使用这些参数,请阅读此问题.
If you need to work with those parameters in prepare()
method, read this question.
这篇关于使用 OGNL 在 Struts 2 中创建具有 2 个动作参数的动态 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!