0

在什么情况下使用 DispatchActions 比使用 Action 更好?

4

1 回答 1

0

当您需要在同一个 struts 模块中使用类似表单 bean 的许多类似操作时(例如,create read update delete对同一对象的 CRUD 操作)。使用plain Action,您将需要4 个带有导入、标题、方法签名的Struts 动作文件:

// CreateAction.java
package com.example.package;
// imports and header
public class CreateAction extends Action {
    public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
        // actual code
    }
}

// ReadAction.java
package com.example.package;
// imports and header
public class ReadAction extends Action {
    public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
        // actual code
    }
}

// UpdateAction.java
package com.example.package;
// imports and header
public class UpdateAction extends Action {
    public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
        // actual code
    }
}

// DeleteAction.java
package com.example.package;
// imports and header
public class DeleteAction extends Action {
    public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
        // actual code
    }
}

此外,您还需要 4 个动作映射struts-config.xml(当然,如果您不使用注释)。但实际上它们只会调用下一层代码(manager/DAO/etc),它独立于 Web(来自请求/响应/映射类),因此可以通过单元测试进行测试,从而实现测试驱动开发和代码可重用性。所有四个类仅在 1-2 行代码上有所不同。其余的都是样板,一次又一次地重复。

通过在 HTTP 请求中添加附加参数或重用现有参数(换句话说:在 JSP 表单标记中),您可以将所有 4 个操作打包在一个类中,例如EventDispatchAction

// CRUDAction.java
package com.example.package;
// imports and header
public class CRUDAction extends EventDispatchAction {
    public ActionForward create(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
        // actual code
    }

    public ActionForward read(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
        // actual code
    }

    public ActionForward update(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
        // actual code
    }

    public ActionForward delete(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
        // actual code
    }
}

这需要更少的样板。为了告诉您要执行哪个操作,您可以使用提交按钮:

<html:submit property="update" value="Save" />
<html:submit property="delete" value="Delete" />
于 2012-11-26T22:55:37.050 回答