我试图让我的Struts2应用程序重定向到一个生成的URL。在这种情况下,我希望URL使用当前日期,或者我在数据库中查找的日期。所以/section/document
变成/section/document/2008-10-06
如何在Struts 2中做动态URL重定向?
这样做的最好方法是什么?
我试图让我的Struts2应用程序重定向到一个生成的URL。在这种情况下,我希望URL使用当前日期,或者我在数据库中查找的日期。所以/section/document
变成/section/document/2008-10-06
如何在Struts 2中做动态URL重定向?
这样做的最好方法是什么?
下面是我们如何做到这一点:
在struts.xml中,有一个动态的结果,如:
<result name="redirect" type="redirect">${url}</result>
在行动:
private String url;
public String getUrl()
{
return url;
}
public String execute()
{
[other stuff to setup your date]
url = "/section/document" + date;
return "redirect";
}
实际上,你可以使用相同的技术,使用OGNL为struts.xml中的任何变量设置动态值。我们已经创建了各种各样的动态结果,包括像RESTful链接这样的东西。很酷的东西。
我最终在调用super.doExecute()
之前完成了Struts的ServletRedirectResult
的子类化并覆盖了它的doExecute()
方法来完成我的逻辑。它看起来像这样:
public class AppendRedirectionResult extends ServletRedirectResult {
private DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
@Override
protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
String date = df.format(new Date());
String loc = "/section/document/"+date;
super.doExecute(loc, invocation);
}
}
我不确定这是否是最好的方法来做到这一点,但它的工作原理。
你也可以使用annotations
和公约的插件,以避免重复的struts.xml配置:
@Result(location="${url}", type="redirect")
的$ {url}的意思是“使用getURL方法的价值”
如果有人想直接ActionClass
重定向:
public class RedirecActionExample extends ActionSupport {
HttpServletResponse response=(HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
url="http://localhost:8080/SpRoom-1.0-SNAPSHOT/"+date;
response.sendRedirect(url);
return super.execute();
}
编辑:添加缺少的报价。
您可以重定向到使用注释另一个动作 -
人们可以直接从一个拦截器重定向到没有它参与的行动方面。
在struts.xml中
<global-results>
<result name="redir" type="redirect">${#request.redirUrl}</result>
</global-results>
在拦截
@Override
public String intercept(ActionInvocation ai) throws Exception
{
final ActionContext context = ai.getInvocationContext();
HttpServletRequest request = (HttpServletRequest)context.get(StrutsStatics.HTTP_REQUEST);
request.setAttribute("redirUrl", "http://the.new.target.org");
return "redir";
}
非常感谢,这很好地工作!有没有办法对xml进行更改,以便它不需要应用于我拥有的每一个动作?我理想的情况是适用于我所有的行为。 – Chris 2009-11-24 04:51:52
你可能会尝试一个全局结果。我还没有为动态变量做过这方面的实验,但只要该操作返回结果,我就不会看到任何不可行的原因。 – 2009-12-04 18:12:40
这项工作的全球业绩很好。 – 2013-05-15 18:05:02