I have this code in my JSP:
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
..
..
<html:form action="update" >
..
..
<html:submit value="delete" />
<html:submit value="edit" />
<html:sumit value="update" />
</html:form>
And this in the struts-config.xml
file:
<action path="/delete" name="currentTimeForm" input="/viewall.jsp" type="com.action.DeleteProduct">
<forward name="success" path="/viewall.jsp" />
<forward name="failure" path="/viewall.jsp" />
</action>
Like the delete
action, I have edit
and update
. It works fine, if I give the name specifically like <html:form action="delete">
but, how to make it dynamically work for update
and edit
?
You have one form and multiple submit buttons. The problems is that a form can only submit to one action, no matter how many submit buttons you have inside the form.
Three solutions come to mind right now:
1. Have just one action where you submit everything. Once inside the Action class check what button was used to submit the form and perform the appropriate treatment based on that.
<html:form action="modify">
..
..
<html:submit value="delete"/>
<html:submit value="edit" />
<html:sumit value="update" >
</html:form>
In the ModifyAction.execute(...)
method have something like:
if (request.getParameter("delete") != null || request.getParameter("delete.x") != null) {
//... delete stuff
} else if (request.getParameter("edit") != null || request.getParameter("edit.x") != null) {
//...edit stuff
} else if (request.getParameter("update") != null || request.getParameter("update.x") != null) {
//... update stuff
}
2. Have the action attribute of the HTML form changed using JavaScript before submitting the form. You first change the submit buttons to plain ones with click handlers attached:
<html:form action="whatever">
..
..
<html:button value="delete" onclick="submitTheForm('delete.do')" />
<html:button value="edit" onclick="submitTheForm('edit.do')" />
<html:button value="update" onclick="submitTheForm('update.do')" />
</html:form>
With the handler:
function submitTheForm(theNewAction) {
var theForm = ... // get your form here, normally: document.forms[0]
theForm.action = theNewAction;
theForm.submit();
}
3. Use a DispatchAction
(one Action class similar to point 1) but without the need to test for what button was clicked since that's treated by the DispatchAction
.
You just provide three execute methods properly named delete
, edit
and update
. Here is an example that explains how you might do it.
In conclusion: For number 1, I don't really like those ugly tests.... for number 2, I don't really like the fact that you have to play with the action form using JavaScript, so I would personally go for number 3.