通常一个Action只能完成一个业务操作,因此,如果要完成多个业务操作,则需要多个Action,如图所示:
Action处理请求的模型图
为了减少重复编程,使应用更加便于维护,我们建议使用DispatchAction(Action的子类)
DispatchAction处理请求的模型图
DispatchAction的使用:
其实DispatchAction就是在struts-config.xml中用parameter参数配置一个表单字段名,这个字段的值就是最终替代execute被调用的方法。例如parameter=“method”,如果method的值为save。Struts的请求将根据parameter的值分发到“save()”方法。注意save()方法的声明和execute()方法的声明必须一致。
struts-config.xml
<span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="stuForm" type="com.java.struts.domain.StudentForm" />
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings>
<action path="/student"
parameter="method"
name="stuForm"
type="com.java.struts.action.StudentAction">
<forward name="toGetList" path="/student.do?method=getAll" />
<forward name="toList" path="/list.jsp" />
<forward name="toEdit" path="/edit.jsp" />
</action>
</action-mappings>
<message-resources parameter="ApplicationResources" />
</struts-config></span>
JSP的insert.jsp界面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'insert.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<form action="student.do?method=save" method="post">
<table>
<tr>
<td align="right">姓名:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td align="right">班级:</td>
<td><input type="text" name="classes"></td>
</tr>
<tr>
<td align="right">分数:</td>
<td><input type="text" name="score"></td>
</tr>
<tr>
<td align="center" colspan="2"><input type="submit" value="添加"><input type="reset" value="重置"><a href="student.do?method=getAll">查看全部信息</a></td>
</tr>
</table>
</form>
</body>
</html>
DispatchAction
public ActionForward save(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
StudentForm studentForm = (StudentForm) form;
Student stu = new Student();
PropertyUtils.copyProperties(stu, studentForm);
boolean flag = studentService.save(stu);
return mapping.findForward("toGetList");
}