如何在Struts 2中进行动态URL重定向?
我正在尝试将我的Struts2应用程序重定向到生成的URL。 在这种情况下,我希望URL使用当前日期或我在数据库中查找的日期。 所以/section/document
成为/section/document/2008-10-06
最好的方法是什么?
我们是这样做的:
在Struts.xml中,有一个动态结果,例如:
${url}
在行动中:
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(); }
编辑:添加了缺失的报价。
我最终super.doExecute()
了Struts的ServletRedirectResult
并在调用super.doExecute()
之前重写了它的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中
${#request.redirUrl}
在拦截器中
@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"; }