我正在尝试将我的Struts2应用重定向到生成的网址。在这种情况下,我希望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 ,并在调用 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中

    <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";
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top