从JSP按钮调用Java类onclick

时间:2013-06-21 14:27:44

标签: java html jsp

我试图在从JSP点击按钮时调用Java类。在我的JSP文件中,我有以下内容:

<%
  Object name = session.getAttribute("name");
  Object ext = session.getAttribute("ext");
  DBOps ops = new DBOps();
  ReturnGetDisplayInfo GDI = ops.getDisplayInfo(ext); 
%>

我在DBOps中有一个方法会删除某个字段,所以我在表格中添加了一个显示信息的按钮,现在我试图在单击按钮时调用delete方法。所以我尝试了以下但是没有用。

<td><button onclick=<% ops.delete(ext); %>>Delete</button></td>

我正在查看一些使用javascript的示例,但它在脚本中使用了defiend函数,而不是调用Java类。

提前致谢

2 个答案:

答案 0 :(得分:0)

你不能直接这样做。您需要往服务器的往返。

最好的选择是AJAX

  • 创建一个servlet,处理在调用某个url时执行删除请求
  • 使用jQuery(或本机XmlHttpRequest)来调用该网址

DWR - direct web remoting也是一个选项,使用AJAX实现)

答案 1 :(得分:0)

我的代码的一个例子,在javascript和ajax中,如果它可以帮助你:

在我的jsp上我有一个onClick“changeTimeZone(org)”

使用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();

}
相关问题