从 JSP 按钮 onclick 调用 Java 类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17237729/
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
Calling Java class from JSP button onclick
提问by laitha0
I am trying to to call a Java class when a button gets clicked from JSP. inside my JSP file I have the following:
当从 JSP 单击按钮时,我试图调用 Java 类。在我的 JSP 文件中,我有以下内容:
<%
Object name = session.getAttribute("name");
Object ext = session.getAttribute("ext");
DBOps ops = new DBOps();
ReturnGetDisplayInfo GDI = ops.getDisplayInfo(ext);
%>
I have a method in DBOps that will delete a certain field so I added a button to teh table that displays the information and now I am trying to call the delete method when the button is clicked. so I tried doing the following but it did not work.
我在 DBOps 中有一个方法可以删除某个字段,所以我在表中添加了一个按钮来显示信息,现在我试图在单击按钮时调用删除方法。所以我尝试执行以下操作,但没有奏效。
<td><button onclick=<% ops.delete(ext); %>>Delete</button></td>
I was looking at some examples that utilize javascript but it uses defiend functions in teh script rather than calling the Java class.
我正在查看一些使用 javascript 的示例,但它在脚本中使用 defiend 函数而不是调用 Java 类。
Thanks in advance
提前致谢
回答by Bozho
You can't do that directly. You need a roundtrip to the server.
你不能直接这样做。您需要往返服务器。
The best option for that is AJAX:
最好的选择是AJAX:
- make a servlet that handles performs the delete request when a certain url is invoked
- use jQuery(or native XmlHttpRequest) to invoke that url
- 当调用某个 url 时,制作一个处理删除请求的 servlet
- 使用jQuery(或本机 XmlHttpRequest)调用该 url
(DWR - direct web remotingis also an option, which is implemented using AJAX)
(DWR - 直接网络远程处理也是一种选择,它是使用 AJAX 实现的)
回答by TroyAndAbed
One example of my code, in javascript and ajax, if it can help you:
我的代码的一个示例,在 javascript 和 ajax 中,如果它可以帮助您:
On my jsp i have a onClick"changeTimeZone(org)"
在我的 jsp 上,我有一个 onClick"changeTimeZone(org)"
Javascript:
Javascript:
function changeTimeZone(org)
{
//Prepare a new ajaxRequest.
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
//state 4 is response ready.
//Status 200 is page found.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//fill the timezone field with the reponse of my servlet.
document.getElementById('timeZoneText').value = xmlhttp.responseText;
}
};
//send an ajax request.
//Go to my servlet
xmlhttp.open('GET','mainServlet?command=ajax.ChangeTimeZone&Org=' + org.value, true);
xmlhttp.send();
}