在什么情况下使用DispatchActions比使用Action更好?
答案 0 :(得分:0)
当你需要在同一个struts模块中使用类似表单bean的许多类似操作时(例如,对create
read
update
delete
同一个对象的CRUD操作)。使用普通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
}
}
此外,您需要struts-config.xml
中的4个动作映射(当然,如果您不使用annotations)。但实际上它们只会调用下一层代码(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" />