如何检测单个Action类中多个提交按钮场景中单击的提交按钮?
发布时间:2020-12-14 23:33:45 所属栏目:Java 来源:网络整理
导读:我在jsp中有一个表单.有两个提交按钮:“搜索”和“添加新”按钮. s:form name="searchForm" action="employeeAction" method="post" s:textfield name="id" label="Employee ID"/ s:textfield name="name" label="Employee Name"/ s:submit value="Search"/
我在jsp中有一个表单.有两个提交按钮:“搜索”和“添加新”按钮.
<s:form name="searchForm" action="employeeAction" method="post"> <s:textfield name="id" label="Employee ID"/> <s:textfield name="name" label="Employee Name"/> <s:submit value="Search"/> <s:submit value="Add New"/> </s:form> 在struts.xml中 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <default-action-ref name="index" /> <global-results> <result name="error">/error.jsp</result> </global-results> <global-exception-mappings> <exception-mapping exception="java.lang.Exception" result="error"/> </global-exception-mappings> </package> <package name="example" namespace="/example" extends="default"> <action name="employeeAction" class="example.EmployeeAction"> <result name="search">/example/search.jsp</result> <result name="add" type="redirect">/example/add.jsp</result> </action> </package> </struts> 在Struts Action类中,我们知道只有一个处理http请求的方法,即execute()方法. 在我预期的情况下,当我单击“搜索”按钮时,它将执行搜索数据并将数据呈现到/example/search.jsp,当我单击“添加新按钮”时,它将执行将页面重定向到/example/add.jsp.但是,单击时两个按钮都将进入execute()方法.所以我需要知道如何检测execute()方法中单击的按钮. 场景看起来像这样 public class EmployeeAction extends ActionSupport { public String execute() throws Exception { //PSEUDOCODE //IF (submitButton is searchButton) // return doSearch(); //ELSE IF (submitButton is addNewButton) // return doAddNew(); return SUCCESS; } public String doSearch() throws Exception { //perform search logic here return "search"; } public String doAddNew() throws Exception { return "add"; } } 解决方法
您可以在struts.xml文件中定义两个操作,并使用< s:submit>的操作属性.标记以便提交到
http://struts.apache.org/docs/submit.html的不同操作.
在JSP中: <s:submit value="Search" action="searchEmployeeAction"/> <s:submit value="Add New" action="addEmployeeAction"/> 在struts.xml中: <action name="addEmployeeAction" method="add" class="example.EmployeeAction"> <result>/example/add.jsp</result> </action> <action name="searchEmployeeAction" method="search" class="example.EmployeeAction"> <result>/example/search.jsp</result> </action> 并在您的操作中创建两个公共String方法添加和搜索. 阅读有关多个提交按钮http://struts.apache.org/docs/multiple-submit-buttons.html的信息. 更新 从Struts2版本2.3.15.3开始,您需要将struts.mapper.action.prefix.enabled常量设置为true,以便启用对action的支持:prefix. 把它放在你的struts.xml文件中: <constant name="struts.mapper.action.prefix.enabled" value="true" /> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |