速動畫教程第十三集
下載地址:http://sonic.peakle.net/download/sonic013.rar
Struts 之 DispatchAction
介紹
DispatchAction就是在struts-config中用parameter參數(shù)配置一個表單字段名,這個字段的值就是最終替代execute被調(diào)用的方法。
例如parameter="method"而request.getParameter("method")="save",其中"save"就是MethodName。struts的請求將根據(jù)parameter被分發(fā)到"save"或者"edit"或者什么。但是有一點(diǎn),save()或者edit()等方法的聲明和execute必須一模一樣。
新建工程:test
添加Struts框架
創(chuàng)建index.jsp
按下Ctrl + N ,創(chuàng)建add.jsp、UsersAction.java
ActionForm采用動態(tài)的ActionForm,所以繼承于DynaActionForm
UserAction的內(nèi)容將包含add、delall等方法,并且繼承于DispatchAction
* 記得修改AddAction.java 為 UsersAction
<action
attribute="addForm"
input="/add.jsp"
name="addForm"
parameter="method"
path="/add"
scope="request"
validate="false"
type="com.test.struts.action.UsersAction" />
* 綠色字全部份為參數(shù)
新建一個forward,名稱為indexGo,并指向index.jsp,將Relative設(shè)置為true
修改add.jsp文件
<html:form action="/add">
username : <html:text property="username"/><html:errors property="username"/><br/>
<html:submit onclick="document.forms[0].action='add.do?method=add';document.forms[0].submit();"/><html:cancel/>
</html:form>
* 綠色字為修改部份
修改后的提交方式是帶參數(shù)提交的,不過必須點(diǎn)提交按鈕,如果是使用回車鍵的話就不會帶有參數(shù)
修改UsersAction.java文件
增加以下代碼:
public ActionForward add(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
DynaActionForm addForm = (DynaActionForm) form;
String username = addForm.getString("username");
// 驗證用戶輸入
if (username == null || username.length() < 1)
mapping.getInputForward();
HttpSession session = request.getSession();
// 從session中獲得數(shù)據(jù)
Vector users = (Vector) session.getAttribute("Users");
if (users == null)
users = new Vector();
users.addElement(username);
session.setAttribute("Users", users);
return mapping.findForward("indexGo");
}
修改index.jsp文件,使頁面中可以顯示session中的數(shù)據(jù),代碼如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic"%>
<html>
<head>
<title>INDEX</title>
</head>
<body>
<a href="add.jsp">ADD USER</a><br>
<a href="delete.jsp">DELETE ALL</a><p>
<logic:present name="Users">
<logic:iterate id="element" name="Users">
<bean:write name="element"/><br>
</logic:iterate>
</logic:present>
</body>
</html>
按下Ctrl + N ,創(chuàng)建DellallAction.java,繼承于DispatchAction
選中:Use existing Action class,瀏覽UsersAction
選中:Parameter選項卡,填入method,然后完成
現(xiàn)在修改index.jsp文件
<a href="delete.jsp">DELETE ALL</a><p>
改為
<a href="delall.do?method=delall">DELETE ALL</a><p>
修改UsersAction.java文件
增加以下代碼:
public ActionForward delall(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
HttpSession session=request.getSession();
session.setAttribute("Users",null);
return mapping.findForward("indexGo");
}
這一步很重要,execute 方法必須刪除!!!
好了,可以進(jìn)行測試了!!!