Java 如何找出在我的 servlet 中按下了哪个 HTML 按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1054543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find out which HTML button was pushed in my servlet?
提问by Nipun
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?
我正在创建一个包含两个提交按钮的注册表单。我需要知道在我的 servlet 代码的表单中单击了哪个按钮?
采纳答案by Vinko Vrsalovic
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!
}
回答by Ratnesh Maurya
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.
您可以在表单中添加一个隐藏字段,当用户单击按钮时,在 sumbit 之前使用 javascript 将其值设置为“btn1”或“btn2”。
Cheers :)
干杯:)
回答by Quentin
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.
然后,服务器端,检查动作数据的值。
回答by Govind Kumar
Use This Code...
使用此代码...
In JSP File...
在 JSP 文件中...
<form action="MyServ">
<input type="submit" name="btn1" value="OK">
<input type="submit" name="btn2" value="OK">
</form>
In Servlet File..
在 Servlet 文件中..
if (request.getParameter("btn1") != null){
// do something
}
else if (request.getParameter("btn2") != null){
// do something
}