使用這種方式也需要通過請求參來來指定要執行的動作。請求參數名的格式為
action!method.action
注:由於Struts2只需要參數名,因此,參數值是什麼都可以。
下面我就給出一個實例程序來演示如何處理有多個submit的form:
主頁面more_submit.jsp
復制代碼 代碼如下:
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>My JSP 'hello.jsp' starting page</title>
</head>
<body>
<s:form action="submit.action">
<s:textfield name="msg" label="輸入內容" />
<s:submit name="save" value="保存" align="left" method="save" />
<s:submit name="print" value="打印" align="left" method="print" />
</s:form>
</body>
</html>
MoreSubmitAction.java
復制代碼 代碼如下:
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;
}
}
structs.xml
復制代碼 代碼如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.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>
result.jsp
復制代碼 代碼如下:
<%@ page language="java" contentType="text/html; charset=GBK"
pageEncoding="GBK"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>提交結果</title>
</head>
<body>
<h1>${result }</h1>
</body>
</html>