终于搞定了dispatchAction.现将步骤总结如下:
JSP方面。没有更多的要求。重要的是在JSP里要用JS对传到ACTION里的隐藏表单元素'action'进行操作赋值。
ACTION里通过提取值进行跳转到相关的方法。如delete,save.
代码如下:
//testDispatchAction.jsp
<%@ page contentType="text/html; charset=GBK" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html>
<head>
<title>
testDispatchAction
</title>
<script>
function setAction(ActionValue)
{
document.forms[0].elements['action'].value = ActionValue;
//alert(document.forms[0].elements['action'].value);
return;
}
</script>
</head>
<body bgcolor="#ffffff">
<html:form action="/testDispatchAction.do" method="POST">
<html:hidden property="action"/>
<html:submit οnclick="setAction('save')" value="save"/>
<html:submit οnclick="setAction('delete')" value="delete"/>
</html:form>
<%
String action = (String)request.getAttribute("action");
out.print(action);
%>
</body>
</html>
----------------------------------------------------------------
//testDispatchAction.java
继承dispatchAction方法。因为execute方法是一定会执行的。所以在execute中提取JSP中的ACTION元素的值。
用dispatchMethod方法跳转到相关的方法。进行操作。(需要注意的是。我总把参数ActionMapping,ActionForm的位置搞反,这
样不会提示出任何错误。但无法跳转到目地页。会出现一个空白的网页。)
package com.scgl.user.action;
import org.apache.struts.action.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.scgl.javabean.Book;
import java.util.ArrayList;
import org.apache.struts.actions.DispatchAction;
import javax.servlet.http.HttpSession;
public class testDispatchAction extends DispatchAction {
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws java.lang.Exception
{
String targetUrl = "failure";
String action = request.getParameter("action");
System.out.println("------------------------------->"+action);
request.setAttribute("action",action);
// return mapping.getInputForward();
// return (mapping.findForward(targetUrl));
// action = (action == null || action.trim().equals("")) ? "init" : action;
return dispatchMethod(mapping, form, request,
response, action);
// String action = request.getParameter("action");
// request.setAttribute("action",action);
// System.out.println("------------------------------->"+action);
// return mapping.getInputForward();
}
public ActionForward save(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception
{
String action = request.getParameter("action");
request.setAttribute("action",action);
System.out.println("这是sava方法");
return mapping.getInputForward();
}
public ActionForward delete(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception
{
String action = request.getParameter("action");
request.setAttribute("action",action);
System.out.println("这是delete方法");
return mapping.getInputForward();
}
}