介绍
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 οnclick="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 方法必须删除!!!
好了,可以进行测试了!!!