2

を使用して軽量のWebインターフェイスを作成しようとしています

サーバーをホストするための埋め込み桟橋と、メインページを表示するための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を使用して開発しているので、アプレットを使用することはできません。Webインターフェイスをできるだけ軽量にしたいと思います。

編集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();
4

2 に答える 2

2

あなたが探しているテクニックはAJAXです。JavaScriptはクライアント側のコードであり、Javaはサーバー上で実行されるコードであるため、サーバーとの間でデータを取得する唯一の方法は、サーバーに対してHTTP要求を行ってデータを要求することです。

以下は、AJAX入門に関するMozillaDeveloperCenterページの例です。

 <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アプリケーションにサーブレットが必要です。

Embedded Jettyサイトには、ハンドラーを作成する方法の例があります。これを使用して、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>");
    }
}
于 2012-05-28T04:18:51.187 に答える
1

Javascript内でJavaメソッドを呼び出すことはできません。

サーバー側でJavaがレンダリングされ、クライアント側でJavaScriptがレンダリングされます(主にWebブラウザー)

両方とも、お互いについての知識を持っていません。

最善の方法は、リンク、フォーム送信、またはAJAXを介して、JSPまたはサーブレット、あるいは該当するものを呼び出すことです。これにより、特定のJavaメソッドが呼び出されます。

于 2012-05-28T04:19:33.010 に答える