介紹
DispatchAction就是在struts-config中用parameter參數配置一個表單字段名,這個字段的值就是最終替代execute被調用的方法。
例如parameter="method"而request.getParameter("method")="save",其中"save"就是MethodName。struts的請求將根據parameter被分發到"save"或者"edit"或者什麼。可是有一點,save()或者edit()等方法的聲明和execute必須如出一轍。
新建工程:test
添加Struts框架
建立index.jsp
按下Ctrl + N ,建立
add.jsp
、
UsersAction.java
ActionForm採用動態的ActionForm,因此繼承於
DynaActionForm
UserAction
的內容將包含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.
Users
Action"
/>
* 綠色字所有份爲參數
新建一個
forward
,名稱爲
indexGo,
並指向
index.jsp,
將
Relative
設置爲
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>
* 綠色字爲修改部份
修改後的提交方式是帶參數提交的,不過必須點提交按鈕,若是是使用回車鍵的話就不會帶有參數
修改
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中得到數據
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中的數據,代碼以下:
<%@
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 ,建立
DellallAction.java,
繼承於
DispatchAction
選中:
Use existing Action class,
瀏覽
UsersAction
選中:
Parameter
選項卡,填入
method
,而後完成
如今修改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 方法必須刪除!!!
好了,能夠進行測試了!!!