【相关文章】
- Struts2教程1:***个Struts2程序
- Struts2教程3:struts.xml常用配置解析
- Struts2教程4:使用validate方法验证数据
- Struts2教程5:使用Validation框架验证数据
- Struts2教程6:在Action类中获得HttpServletResponse对象
- Struts2教程7:上传任意多个文件
- Struts2教程8:拦截器概述
- Struts2教程9:实现自已的拦截器
- Struts2教程10:国际化
|
由于在<form>中的多个提交按钮都向一个action提交,使用Struts2 Action的execute方法就无法判断用户点击了哪一个提交按钮。如果大家使用过Struts1.x就会知道在Struts1.2.9之前的版本需要使用一个LookupDispatchAction动作来处理含有多个submit的form。但使用LookupDispatchAction动作需要访问属性文件,还需要映射,比较麻烦。从Struts1.2.9开始,加入了一个EventDispatchAction动作。这个类可以通过java反射来调用通过request参数指定的动作(实际上只是判断某个请求参数是不存在,如果存在,就调用在action类中和这个参数同名的方法)。使用EventDispatchAction必须将submit的name属性指定不同的值以区分每个submit。而在Struts2中将更容易实现这个功能。
当然,我们也可以模拟EventDispatchAction的方法通过request获得和处理参数信息。但这样比较麻烦。在Struts2中提供了另外一种方法,使得无需要配置可以在同一个action类中执行不同的方法(默认执行的是execute方法)。使用这种方式也需要通过请求参来来指定要执行的动作。请求参数名的格式为
action!method.action
注:由于Struts2只需要参数名,因此,参数值是什么都可以。
下面我就给出一个实例程序来演示如何处理有多个submit的form:
【第1步】实现主页面(more_submit.jsp)
|
在more_submit.jsp中有两个submit:保存和打印。其中分别通过method属性指定了要调用的方法:save和print。因此,在Action类中必须要有save和print方法。
#p#
【第2步】实现Action类(MoreSubmitAction)
packageaction;
importjavax.servlet.http.*;
importcom.opensymphony.xwork2.ActionSupport;
importorg.apache.struts2.interceptor.*;
publicclassMoreSubmitActionextendsActionSupportimplementsServletRequestAware
{
privateStringmsg;
privatejavax.servlet.http.HttpServletRequestrequest;
//获得HttpServletRequest对象
publicvoidsetServletRequest(HttpServletRequestrequest)
{
this.request=request;
}
//处理savesubmit按钮的动作
publicStringsave()throwsException
{
request.setAttribute("result","成功保存["+msg+"]");
return"save";
}
//处理printsubmit按钮的动作
publicStringprint()throwsException
{
request.setAttribute("result","成功打印["+msg+"]");
return"print";
}
publicStringgetMsg()
{
returnmsg;
}
publicvoidsetMsg(Stringmsg)
{
this.msg=msg;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
上面的代码需要注意如下两点:
save和print方法必须存在,否则会抛出java.lang.NoSuchMethodException异常。
Struts2 Action动作中的方法和Struts1.x Action的execute不同,只使用Struts2 Action动作的execute方法无法访问request对象,因此,Struts2 Action类需要实现一个Struts2自带的拦截器来获得request对象,拦截器如下:
org.apache.struts2.interceptor. ServletRequestAware
【第3步】配置Struts2 Action
struts.xml的代码如下:
|
【第4步】编写结果页(result.jsp)
|
在result.jsp中将在save和print方法中写到request属性中的执行结果信息取出来,并输出到客户端。
【编辑推荐】