在很多Web应用中,为了完成不同的工作,一个HTML form标签中可能有两个或多个submit按钮,如下面的代码所示:
- <html action="..." method="post">
- ... ...
- <input type="submit" value="保存" />
- <input type="submit" value="打印" />
- </html>
由于在<form>中的多个提交按钮都向一个action提交,使用Struts2 Action的execute方法就无法判断用户点击了哪一个提交按钮。
请求参数名的格式为
action!method.action
【第2步】实现Action类(MoreSubmitAction)
- package action;
- import javax.servlet.http.*;
- import com.opensymphony.xwork2.ActionSupport;
- import org.apache.struts2.interceptor.*;
- public class MoreSubmitAction extends ActionSupport implements ServletRequestAware
- {
- private String msg;
- private javax.servlet.http.HttpServletRequest request;
- // 获得HttpServletRequest对象
- public void setServletRequest(HttpServletRequest request)
- {
- this.request = request;
- }
- // 处理save submit按钮的动作
- public String save() throws Exception
- {
- request.setAttribute("result", "成功保存[" + msg + "]");
- return "save";
- }
- // 处理print submit按钮的动作
- public String print() throws Exception
- {
- request.setAttribute("result", "成功打印[" + msg + "]");
- return "print";
- }
- public String getMsg()
- {
- return msg;
- }
- public void setMsg(String msg)
- {
- this.msg = msg;
- }
- }
【第3步】配置Struts2 Action,struts.xml如下:
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
- "http://struts.apache.org/dtds/struts-2.0.dtd">
- <struts>
- <package name="demo" extends="struts-default" >
- <action name="submit" class="action.MoreSubmitAction">
- <result name="save" >
- /result.jsp
- </result>
- <result name="print">
- /result.jsp
- </result>
- </action>
- </package>
- </struts>
【第4步】编写结果页(result.jsp)
- <%@ page pageEncoding="GBK"%>
- <html>
- <head>
- <title>提交结果</title>
- </head>
- <body>
- <h1>${result}</h1>
- </body>
- </html>
在result.jsp中将在save和print方法中写到request属性中的执行结果信息取出来,并输出到客户端。
启动Tomcat后,在IE中执行如下的URL来测试程序:
http://localhost:8080/moresubmit/more_submit.jsp
大家也可以直接使用如下的URL来调用save和print方法:
调用save方法:http://localhost:8080/moresubmit/submit!save.action
调用print方法:http://localhost:8080/moresubmit/submit!print.action
时间: 2024-12-28 01:33:04