从javascript调用java方法

时间:2012-05-28 04:12:51

标签: java javascript jetty

我正在尝试使用

创建一个轻量级的Web界面

嵌入式jetty托管服务器, 和一个带有java脚本的简单html代码来显示主页面,因为页面不是静态的,这取决于我需要调用java代码的条件。示例html代码如下:

 <body>
<script type="text/javascript">
 function myfunction(frm)
{
  var opt=frm.option.value;
  alert("option is"+frm.option.value);
   // call a java method depending on the value of opt
  frm.option.value="";
 }
</script>
    <h1 style="text-align: center;">Agent Management Interface</h1>
    <ol>

    </ol>
    <form name="management_form">
            Enter Option: <input type="text" id="optiontb" name="option">
            <input type="button" onclick="myfunction(this.form)" value="submit">
    </form>
</body>
</html>

我不确定此问题是否早先发布过,但我想知道是否有一种方法可以将变量传递给用户定义的java代码并获取返回值并在Web界面上显示它们?

我读了一下我没有使用任何外部工具,使用eclipse开发,使用applet不是一个选项。我希望网页界面尽可能轻。

编辑2:

我已经使用下面给出的建议更新了html文件,但这对我来说似乎没有用。我怀疑是因为我编写处理程序的方式,日志消息是:

2012-05-28 16:02:53.753:DBUG:oejs.AsyncHttpConnection:async request (null null)@16471729 org.eclipse.jetty.server.Request@fb56b1
2012-05-28 16:02:53.754:DBUG:oejs.Server:REQUEST / on org.eclipse.jetty.server.nio.SelectChannelConnector$SelectChannelHttpConnection@bc8e1e@127.0.0.1:8080<->127.0.0.1:47830
2012-05-28 16:02:53.756:DBUG:oejs.Server:RESPONSE /  304
2012-05-28 16:02:53.757:DBUG:oejs.AsyncHttpConnection:async request (null null)@16471729 org.eclipse.jetty.server.Request@fb56b1

为处理程序编写的代码如下

System.setProperty("org.eclipse.jetty.util.log.DEBUG","true"); 
    Server server = new Server(8080);
    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setDirectoriesListed(true);
    resource_handler.setResourceBase(args.length == 2?args[1]:".");
    resource_handler.setWelcomeFiles(new String[]{ "index.html" });
    System.out.println("serving " + resource_handler.getBaseResource());

    ContextHandler context0 = new ContextHandler();
    context0.setContextPath("/senddata");
    Handler handler0=new HelloHandler();
    context0.setHandler(handler0);

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(new Handler[]{context0});

    HandlerCollection handlersc = new HandlerCollection();
    handlersc.setHandlers(new Handler[]{resource_handler,new DefaultHandler(), contexts});
    server.setHandler(handlersc);
    server.start();
    server.join();

2 个答案:

答案 0 :(得分:2)

您正在寻找的技术是AJAX。由于JavaScript是客户端代码而Java是在服务器上运行的代码,因此从服务器获取数据的唯一方法是向服务器发出HTTP请求以请求数据。

以下是Mozilla Developer Center page on Getting Started with AJAX

中的示例
 <script type="text/javascript">

  // this is the function that will make the request to the server
  function makeRequest(url) {
    var httpRequest;

    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
      httpRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE
      try {
        httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
      } 
      catch (e) {
        try {
          httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch (e) {}
      }
    }

    if (!httpRequest) {
      alert('Giving up :( Cannot create an XMLHTTP instance');
      return false;
    }

    // here we set the onreadystatechange event to invoke "alertContents"
     // this is called when the response returns. This is a "callback" function.

    httpRequest.onreadystatechange = alertContents;
    httpRequest.open('GET', url);

    // this starts the send operation
    httpRequest.send();
  }

  // here is the callback handler
  function alertContents() {
    if (httpRequest.readyState === 4) {
      if (httpRequest.status === 200) {

        // since the response from the Jetty server is <h1>Hello World</h1>
         // the alert should fire with that markup
        alert(httpRequest.responseText);

    } else {
      alert('There was a problem with the request.');
    }
  }
}

// this is your function, with the makeRequest call. 
function myfunction(frm)
{
    var opt=frm.option.value;
    alert("option is"+frm.option.value);
    // call a java method depending on the value of opt
    frm.option.value="";

    // call makerequest here with your data
    makeRequest('/senddata?value=' + frm.option.value); 
}

</script>

虽然上面的代码允许您从浏览器发出HTTP请求,但您需要在Java应用程序中使用servlet才能接收请求,处理请求并将响应返回给浏览器。 / p>

Embedded Jetty site has an example of how to create a Handler,您可以使用它来检查HTTP请求,处理它并返回响应。我稍微修改了示例以提取您将通过AJAX请求传递的查询参数:

public class HelloHandler extends AbstractHandler
{
    public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) 
        throws IOException, ServletException
    {
        // the value passed in from the client side
        String value = request.getParameter("value");

        // do stuff with that here

        // return a response
        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);

        // this gets sent back down to the client-side and is alerted
        response.getWriter().println("<h1>Hello World</h1>");
    }
}

答案 1 :(得分:1)

您无法在Javascript中调用Java方法。

Java在服务器端呈现,javascript在客户端(主要是Web浏览器)

两者都没有彼此了解。

您可以做的最好的事情是通过链接或表单提交或AJAX调用任何JSP或servlet或其中任何适用的,然后依次为您调用特定的Java方法。