I am creating a registration form which contains two submit buttons. I need to know which button is clicked in the form in my servlet code?
Asked
Active
Viewed 6.5k times
4 Answers
40
Read the answers to this question.
So, in
String button1 = request.getParameter("button1");
String button2 = request.getParameter("button2");
the value which isn't null is the pressed button.
Or, if you want to use the same name for the two buttons you can set a different value
<input type="submit" name="act" value="delete"/>
<input type="submit" name="act" value="update"/>
Then
String act = request.getParameter("act");
if (act == null) {
//no button has been selected
} else if (act.equals("delete")) {
//delete button was pressed
} else if (act.equals("update")) {
//update button was pressed
} else {
//someone has altered the HTML and sent a different value!
}

Community
- 1
- 1

Vinko Vrsalovic
- 330,807
- 53
- 334
- 373
-
how do i do this without making the type = "submit"? Is there way to do this with type="button"? – ace23 Nov 22 '19 at 14:22
4
Only the clicked button will be a successful control.
<input type="submit" name="action" value="Something">
<input type="submit" name="action" value="Something Else">
Then, server side, check the value of the action data.

Quentin
- 914,110
- 126
- 1,211
- 1,335
0
Use This Code...
In JSP File...
<form action="MyServ">
<input type="submit" name="btn1" value="OK">
<input type="submit" name="btn2" value="OK">
</form>
In Servlet File..
if (request.getParameter("btn1") != null){
// do something
}
else if (request.getParameter("btn2") != null){
// do something
}

Govind Kumar
- 1
- 1
-3
You can add a hidden field to the form and when a user clicks a button set its value to "btn1" or "btn2" using javascript before sumbit.
Cheers :)

Ratnesh Maurya
- 706
- 3
- 10
-
3There is no need for JS. You can just do what Google does, have two submit buttons with different values. – Matthew Flaschen Jun 28 '09 at 08:52
-
1
-
3So little code. So many things wrong with it. (1) It can't decide if it wants to be HTML or XHTML. (2) It has spelling errors. (3) It introduces a dependency on JS that simply isn't needed. (4) It uses a loop label without a loop. (5) It goes the long way around to get a reference to the form element. (6) It uses intrinsic event handler attributes instead of separating out the code in to a script file. While it is *a* way of doing it with JS, it is a very poor example of using JS to solve the problem, and JS is the wrong tool to solve the problem with in the first place. – Quentin Jun 28 '09 at 13:05
-
@MatthewFlaschen No, you are wrong. If you site is internationalized, you cannot depend on the value coming through in a reasonable form. The multiple submit buttons with different values idea is a non-starter for internationalized sites. – timthelion May 07 '18 at 08:50