First, here is the code:
<form action="FirstServlet" method="Post">
Last Name: <input type="text" name="lastName" size="20">
<br><br>
<input type="submit" value="FirstServlet">
<input type="submit"value="SecondServlet">
</form>
I’d like to understand how to send information in case the FirstServlet button was pressed to FirstServlet and in case the SecondServlet button was pressed to SecondServlet.
important:
I want to do it in the same form so the same information would be transered to both the servlets. (of course, in the servlets I’ll use the info accordingly)
There are several ways to achieve this.
Probably the easiest would be to use JavaScript to change the form’s action.
But this of course won’t work when the enduser has JS disabled (mobile browsers, screenreaders, etc).
Another way is to put the second button in a different form, which may or may not be what you need, depending on the concrete functional requirement, which is not clear from the question at all.
Note that a form would on submit only send the input data contained in the very same form, not in the other form.
Again another way is to just create another single entry point servlet which delegates further to the right servlets (or preferably, the right business actions) depending on the button pressed (which is by itself available as a request parameter by its
name):with the following in
MainServletThis is only not very i18n/maintenance friendly. What if you need to show buttons in a different language or change the button values while forgetting to take the servlet code into account?
A slight change is to give the buttons its own fixed and unique name, so that its presence as request parameter could be checked instead of its value which would be sensitive to i18n/maintenance:
with the following in
MainServletLast way would be to just use a MVC framework like JSF so that you can directly bind javabean methods to buttons, but that would require drastic changes to your existing code.
with just the following javabean instead of a servlet