例如以下實例:
1.主頁面:more_submit.jsp,該頁面有兩個submit,但在同一個Action類中執行;
1 <%@ page language="java" contentType="text/html; charset=BIG5" 2 pageEncoding="BIG5"%> 3 <%@ taglib prefix="s" uri="/struts-tags" %> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=BIG5"> 8 <title>My Jsp "hello.jsp" starting page</title> 9 </head> 10 <body> 11 <s:form action="submit.action"> 12 <s:textfield name="msg" label="輸入內容"></s:textfield> 13 <s:submit name="save" value="保存" align="left" method="save"></s:submit> 14 <s:submit name="print" value="打印" align="left" method="print"></s:submit> 15 </s:form> 16 </body> 17 </html>
2.Action類,該類要注意兩點:(1)save和print方法必須存在,否則會拋出java.lang.NoSuchMethodException異常;(2)在Struts 2 的Action動作的execute方法中,無法訪問request對象,因此,Struts 2的Action類需要實現一個Struts2自帶的攔截器來獲得request對象,攔截器為:org.apache.struts2.interceptor.ServletRequestAware;
1 package action; 2 3 import javax.servlet.http.*; 4 5 import com.opensymphony.xwork2.ActionSupport; 6 import org.apache.struts2.interceptor.*; 7 8 //save和print方法必須存在,否則會拋出java.lang.NoSuchMethodException異常 9 10 public class MoreSubmitAction extends ActionSupport implements ServletRequestAware { 11 /** 12 * 13 */ 14 private static final long serialVersionUID = 1L; 15 private String msg; 16 public String getMsg() { 17 return msg; 18 } 19 20 public void setMsg(String msg) { 21 this.msg = msg; 22 } 23 24 private javax.servlet.http.HttpServletRequest request; 25 26 //獲得HttpServletRequest對象 27 public void setServletRequest(HttpServletRequest request) 28 { 29 this.request = request; 30 } 31 32 //處理save submit按鈕的動作 33 public String save() throws Exception 34 { 35 request.setAttribute("result", "成功保存["+msg+"]"); 36 return "save"; 37 } 38 39 //處理print submit按鈕的動作 40 public String print() throws Exception 41 { 42 request.setAttribute("result", "成功打印["+msg+"]"); 43 return "print"; 44 } 45 }
3.配置Struts2 Action
1 <package name="demo" extends="struts-default"> 2 <action name="submit" class="action.MoreSubmitAction"> 3 <result name="save">/result.jsp</result> 4 <result name="print">/result.jsp</result> 5 </action> 6 </package>
4.編寫結果頁:result.jsp
1 <%@ page language="java" contentType="text/html; charset=BIG5" 2 pageEncoding="BIG5"%> 3 <%@ taglib prefix="s" uri="/struts-tags" %> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=BIG5"> 8 <title>提交結果</title> 9 </head> 10 <body> 11 <h1> 12 ${msg} 13 </h1> 14 </body> 15 </html>