从Struts1迁移到Struts2

时间:2015-09-07 09:08:47

标签: java struts2 migration struts-1

我正在将应用程序从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)吗?

1 个答案:

答案 0 :(得分:1)

在Struts 1中,您应该从ActionForward方法返回execute。 Struts 2返回类型为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类提供。然后你可以使用代码

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

在JSP中,您可以使用

显示错误
<s:actionerror/>