-->

How to find out which HTML button was pushed in my

2020-05-31 07:40发布

问题:

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?

回答1:

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!
}


回答2:

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.



回答3:

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
 }


回答4:

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 :)