DispatchAction用于分发的Action,主要的好处是把一些功能类似的Action放到一个Action中,通过传入的不同参数来觉得执行哪个操作.
public class OperateAction extends DispatchAction {
public ActionForward add(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("Action.add()");
Cal c = new Cal();
CalForm f =(CalForm)form;
double r = 0.0;
ActionMessages errors = new ActionMessages();
try{
r = c.add(Double.parseDouble(f.getFirst()),Double.parseDouble(f.getSecond()));
}catch(Exception e){
errors.add("num",new ActionMessage("error"));
this.saveErrors(request, errors);
return mapping.findForward("input");
}
f.setResult(r);
return mapping.findForward("result");
}
public ActionForward sub(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("Action.sub()");
return mapping.findForward("result");
}
public ActionForward mul(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("Action.mul()");
return mapping.findForward("result");
}
public ActionForward div(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("Action.div()");
return mapping.findForward("result");
}
}
2. 在struts-config.xml文件中进行配置,为该Action配置parameter属性
<action-mappings >
<action
name="CalForm"
scope="request"
path="/add"
type="com.rhcj.struts.CalAction">
<forward name="result" path="/result.jsp" />
</action>
<action path="/operate"
type="com.rhcj.struts.OperateAction"
name="CalForm"
scope="request"
parameter="operate">
<forward name="result" path="/result.jsp" />
<forward name="input" path="/index.jsp"></forward>
</action>
</action-mappings>
3. 创建页面,页面请求中要有一个参数与parameter属性值一致,如:/operate?operate=add,此处表单中使用隐藏域传值
<input type="hidden" name="operate" value="">
<input type="button" value="+" name="button1"
onclick="doSubmit('add')">
<input type="button" value="-" name="button1"
onclick="doSubmit('sub')">
<input type="button" value="*" name="button1"
onclick=doSubmit('mul');>
<input type="button" value="/" name="button1"
onclick="doSubmit('div')">
<script type="text/javascript">
function doSubmit(oper){
document.forms[0].elements["operate"].value=oper;
document.forms[0].submit();
}
</script>
注意:该页面中隐藏域的name属性<input type="hidden" name="operate">对应于struts-config.xml中DispacthAction配置的parameter属性值
<action path="/operate"
type="com.rhcj.struts.OperateAction"
name="CalForm"
scope="request"
parameter="operate">
<forward name="result" path="/result.jsp" />
</action>
隐藏域的value值要和DispacthAction中的方法名称对应