从 Struts1 迁移到 Struts2

Migrating from Struts1 to Struts2

我正在将应用程序从 Struts 1 迁移到 Struts 2。我遇到了以下代码片段。请让我知道如何替换 Struts 2.

中的代码片段
protected ActionForward getActionForward(FilterContext ctx, String key, boolean redirect) {
    HashMap filterForwards = ctx.getFilterForwards();
    String forwardPage = (String)filterForwards.get(key);
    if(forwardPage == null)
        return null;
    return new ActionForward(forwardPage, redirect);
}

另一个代码片段是这样的:-

protected void setError(HttpServletRequest req, String msg) {
        ActionMessages errors = new ActionMessages();
        errors.add("exception", new ActionMessage(MSG_KEY, msg));
        req.setAttribute(Globals.ERROR_KEY, errors);
    }

我应该用 addActionError(msg) 替换上面的代码吗?

在 Struts 1 中,您应该 return ActionForward 来自 execute 方法。 Struts 2 returns 类型 String 的结果代码。因此,应将 ActionForward 所在的代码替换为结果代码。操作结果应该配置为操作,就像您在 Struts 1 中配置转发一样。

创建两个结果配置:一个是redirectAction结果类型,另一个是dispatcher结果类型。像这样

<result name "redirect" type="redirectAction">${forwardPage}</result>
<result>${forwardPage}</result>

代码应替换为

private String forwardPage; 

public String getForwardPage() { return forwardPage; }

public void setForwardPage(String forwardPage) {
  this.forwardPage = forwardPage;
} 

protected String getActionForward(FilterContext ctx, String key, boolean redirect) {
    HashMap filterForwards = ctx.getFilterForwards();
    String forwardPage = (String)filterForwards.get(key);
    if(forwardPage == null)
        return NONE;
    if (redirect) {
       setForwardPage(forwardPage);
       return "redirect";
    } else {
       setForwardPage(forwardPage)
       return SUCCESS; 
    }
}

错误由您的操作应继承的 ActionSupport class 提供。然后你可以使用代码

protected void setError(String msg) {
    addActionError(getText("exception", new Object[]{msg}));
}

在 JSP 中,您可以使用

显示错误
<s:actionerror/>