代码之家  ›  专栏  ›  技术社区  ›  Sietse

如何在Struts2中进行动态URL重定向?

  •  26
  • Sietse  · 技术社区  · 16 年前

    我正在尝试将struts2应用程序重定向到生成的URL。在这种情况下,我希望URL使用当前日期,或者在数据库中查找的日期。所以 /section/document 变成 /section/document/2008-10-06

    最好的方法是什么?

    6 回复  |  直到 8 年前
        1
  •  61
  •   Johnny Wey    16 年前

    我们是这样做的:

    在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链接之类的内容。很酷的东西。

        2
  •  14
  •   KNU    11 年前

    一个人也可以用 annotations 以及避免struts.xml中重复配置的约定插件:

    @Result(location="${url}", type="redirect")
    

    $url表示“使用geturl方法的值”

        3
  •  3
  •   Tom11    8 年前

    如果有人想直接转到 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(); 
    }
    

    编辑:添加了一个缺少的引号。

        4
  •  2
  •   Sietse    16 年前

    我最终将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);
      }
    }
    

    我不确定这是不是最好的方法,但它是有效的。

        5
  •  1
  •   Stephan    9 年前

    可以使用注释重定向到另一个操作-

    @Result(
        name = "resultName",
        type = "redirectAction",
        params = { "actionName", "XYZAction" }
    )
    
        6
  •  0
  •   Aaron    8 年前

    可以直接从拦截器重定向,而不考虑涉及到哪个操作。

    在Struts中

        <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";
    }