1.页面
<%@page language="java"import="java.util.*"pageEncoding="UTF-8"%>
<%@taglibprefix="s"uri="/struts-tags"%>
<html>
<head>
<title>MyJSP'hello.jsp'startingpage</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>
2.实现Action类(MoreSubmitAction)
代码如下
package action;
import com.opensysphony.xwork2.ActionSupport;
import org.apache.struts2.interceptor.ServletRequestAware;//拦截器
public class MoreSubmitAction extends ActionSupport
implements ServletRequestAware{
private String msg;//the same with from
private javax.servlet.http.HttpServletRequest request;
public void setRequest(javax.servlet.http.HttpServletRequest request) {
this.request = request;
}
public String save()throws Exception{
request.setAttribute("result","save["+msg+"]");
return "save";
}
public String print() throws Exception{
request.setAttribute("result","print["+msg+"]");
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
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. 配置Struts2xml
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEstrutsPUBLIC
"-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.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. 编辑结果页面
<%@pagepageEncoding="UTF-8"%>
<html>
<head>
<title>提交结果</title>
</head>
<body>
<h1>${result}</h1>
</body>
</html>
--转自