2012-05-28 118 views
2

我試圖創建一個使用調用Java方法

嵌入式碼頭到主機的服務器, 並用Java腳本顯示主網頁一個簡單的HTML代碼,重量輕的web界面,因爲網頁不是靜態的,這取決於我需要調用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代碼中的變量,並獲得返回值和顯示的方法他們在網絡界面?

我讀了一點點我沒有使用任何外部工具,使用eclipse開發,使用applet不是一個選項。我希望網頁界面儘可能輕便。

編輯2:

我已經更新了下面給出的建議的HTML文件,但是這似乎並不爲我工作。我懷疑這是因爲我寫的處理方式,日誌信息是:

2012-05-28 16:02:53.753:DBUG:oejs.AsyncHttpConnection:async request (null null)@16471729 [email protected] 
2012-05-28 16:02:53.754:DBUG:oejs.Server:REQUEST/on org.eclipse.jett[email protected][email protected]: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 [email protected] 

爲處理器編寫的代碼如下

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(); 
+0

當你說它不工作,發生了什麼?另外,如果有堆棧痕跡,您是否也可以包含這些內容? – jmort253

+0

@ jmort253 - 哎呀對不起,我忘了提到發生了什麼,localhost:8080加載文本和按鈕,當我鍵入say 1並單擊提交按鈕時,我沒有看到網頁上的任何更改,但只有日誌控制檯中的日誌消息。 – bhavs

+1

好的。調試101。首先,確保你在你的Handler中做了些什麼來打印日誌。 'System.out.println(「Hello world !!!」);'如果你沒有設置日誌記錄,'是一個非常快速的方法。其次,檢查Firebug或Chrome調試器中的NET選項卡,並查看服務器響應,看它是否包含服務器在'response.getWriter.println()'中返回的Hello world。換句話說,您需要通過確定斷開連接的位置來縮小問題的範圍。 – jmort253

回答

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請求,處理請求,並將響應返回給瀏覽器。

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>"); 
    } 
} 
+0

恭喜。在10K :) –

+0

@AndrewThompson - 謝謝!我幾個星期以來一直在不停地這樣做!我的目標是在6月1日之前擊中它:) – jmort253

+1

那麼你確實做到了。請原諒我的語言。 ;) –

1

你不能在JavaScript中調用Java方法。

的Java渲染在服務器端和JavaScript在客戶端(web瀏覽器居多)

兩個,沒有任何關於對方的任何知識。

您可以通過鏈接或表單提交或AJAX調用任何適用的JSP或servlet,然後依次調用特定的Java方法。

+1

1.實際上,您可以在客戶端*上從javascript調用java。2. java可以是客戶端語言(applets)。 javascript可以是一種服務器語言(node.js) * http://docs.oracle.com/javase/tutorial/deployment/applet/invokingAppletMethodsFromJavaScript.html –

+2

我很確定@linuxeasy指的是上下文中的OP的問題:)即「使用小程序是不是一個選項」。 –