我试图让我的 Struts2 应用程序重定向到生成的 URL。在这种情况下,我希望 URL 使用当前日期,或者我在数据库中查找的日期。所以/section/document
变成/section/document/2008-10-06
最好的方法是什么?
我们是这样做的:
在 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 链接之类的东西。酷的东西。
也可以使用annotations
和 Convention 插件来避免 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'ServletRedirectResult
并在调用之前覆盖了它的doExecute()
方法来执行我的逻辑super.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);
}
}
我不确定这是否是最好的方法,但它确实有效。
您可以使用注释重定向到另一个操作 -
@Result(
name = "resultName",
type = "redirectAction",
params = { "actionName", "XYZAction" }
)
可以直接从拦截器重定向,而无需考虑涉及哪个操作。
在 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";
}