首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从java脚本调用java方法

从java脚本调用java方法
EN

Stack Overflow用户
提问于 2012-05-28 12:12:51
回答 2查看 3.3K关注 0票数 2

我正在尝试创建一个轻量级的web界面,使用

用于托管服务器的嵌入式jetty,以及用于显示主页的简单html代码和java脚本,因为根据我需要调用java代码的条件,页面不是静态的。示例html代码如下:

代码语言:javascript
复制
 <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进行开发,使用applets是不可行的。我希望web界面尽可能的轻巧。

编辑2:

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

代码语言:javascript
复制
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

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

代码语言:javascript
复制
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();
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-05-28 12:18:51

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

下面是Mozilla Developer Center page on Getting Started with AJAX中的一个示例

代码语言:javascript
复制
 <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来接收请求、处理请求并将响应返回给浏览器。

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

代码语言:javascript
复制
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>");
    }
}
票数 2
EN

Stack Overflow用户

发布于 2012-05-28 12:19:33

您不能在Javascript中调用Java方法。

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

两者都不了解对方。

您最多只能通过链接、表单提交或AJAX调用任何JSP或servlet或任何适用的方法,这反过来又会为您调用特定的Java方法。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10779258

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档