struts2处理一个form多个submit

web应用中,为完成不同工作,一个jsp的form标签可能有多个submit。如下代码:

<s:form action="submit" method="post" namespace="/my">
<s:textfield name="msg" label="叙述:"></s:textfield>
<s:submit value="保存" name="save" method="save"></s:submit>
<s:submit value="打印" name="print" method="print"></s:submit>
</s:form>

 

多个submit向同一个action提交,struts2中action默认的execute()无法判定哪个submit。

所以需要通过请求参判定执行的动作。

格式:action!method.action

---------------------------------------------------------------------

实例。

---------------------------------------------------------------------

1.index.jsp代码。

 

<%@taglib prefix="s" uri="/struts-tags"%>
...
<s:form action="submit" method="post" namespace="/my">
<s:textfield name="msg" label="叙述:"></s:textfield>
<s:submit value="保存" name="save" method="save"></s:submit>
<s:submit value="打印" name="print" method="print"></s:submit>
</s:form>
 

 

method指定调用struts2中action的方法名。

 

2.action代码。(MoreSubmitAction)

package pro.action;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;
public class MoreSubmitAction extends ActionSupport implements ServletRequestAware{

private String msg;
private HttpServletRequest request;

public MoreSubmitAction(){}
public String getMsg() {
return msg;
}
//获取HttpServletRequest对象
public void setServletRequest(HttpServletRequest request) {
this.request=request;
}
public void setMsg(String msg) {
this.msg = msg;
}
//处理submit save动作
public String save(){
request.setAttribute("msg",msg);
return "success";
}
//处理submit print动作
public String print(){
request.setAttribute("msg",msg);
return "success";
}
}

 

 

3.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="struts2" namespace="/my" extends="struts-default">
<action name="submit" class="pro.action.MoreSubmitAction">
<result name="success">/index.jsp</result>
</action>
</package>
</struts>

 

你可能感兴趣的:(struts2)