2013-03-11 74 views
1

我想從我的Applet發送一些數據到特定的Servlet,該Servlet應該連接到MySQL數據庫並存儲傳輸的數據。 在applet側I用這種方法將數據從傳送小應用程序向servlet:我的applet無法連接到Servlet並傳輸數據

public void sendData() { 
     try { 
      URL postURL = new URL("http://localhost:8080/MyApplet/mydb"); 
      HttpURLConnection conn = (HttpURLConnection) postURL.openConnection(); 
      conn.setRequestMethod("POST"); 
      conn.setDoOutput(true); 
      conn.connect(); 

      String param1 = "data1"; 
      String param2 = "data2"; 
      String param3 = "data3"; 

      PrintWriter out = new PrintWriter(conn.getOutputStream()); 
      out.write("param1=" + URLEncoder.encode(param1, "UTF-8") 
        + "&param2=" + URLEncoder.encode(param2, "UTF-8") 
        + "&param3=" + URLEncoder.encode(param3, "UTF-8")); 
      out.flush(); 


     } catch (Exception e) { 
      System.err.println(e.getMessage()); 
      JOptionPane.showMessageDialog(GameApplet.this, e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE); 
     } 
    } 

哪個MyApplet/mydb的是我Selrvet的路徑。 並在Servlet邊我寫這個代碼:從doGet()doPost()

protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
     response.setContentType("text/html;charset=UTF-8"); 

     String parameter1 = request.getParameter("param1"); 
     String parameter2 = request.getParameter("param2"); 
     String parameter3 = request.getParameter("param3"); 

     connectToDB(); 
     insert(parameter1, parameter2, parameter3); 
//  insert("X", "Y", "Z"); 
     closeDB(); 
} 

processRequest()電話。 當我直接從它的http鏈接調用它並填充數據庫時沒有任何問題,但是當我從applet調用它時,Servlet工作正常,沒有任何反應,甚至沒有任何異常!說實話,他們不能互相溝通,我真的很困惑。

+1

嘗試使用'URLConnection'如示例[這裏](http://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html)所示 – 2013-03-11 20:27:11

+0

我試過這個,但是我無法與Servlet通過Applet呢!當Servlet希望接收數據或Applet想要發送時,似乎有什麼錯誤,因爲當我單獨測試它們時,兩個類都能正常工作! : - ? – 2013-03-11 21:15:43

回答

0

我用這個代碼發送最後一個以上的參數: (這只是一個建議,也許還有更好的解決方案,但它的工作對我來說)

Applet的一面:

URL helloServletURL = new URL(getCodeBase().toString() + "mydb"); 
    URLConnection urlConnection = helloServletURL.openConnection(); 
    urlConnection.setDoInput(true); 
    urlConnection.setDoOutput(true); 
    urlConnection.setUseCaches(false); 

    String param1 = "data1"; 
    String param2 = "data1"; 
    String param3 = "data1"; 

    ObjectOutputStream objOut = new ObjectOutputStream(urlConnection.getOutputStream()); 
    objOut.writeUTF(param1 + "%" + param2 + "%" + param3); 

    objOut.flush(); 

Servlet的一面:

ObjectInputStream dataInput = new ObjectInputStream(request.getInputStream()); 
    String param = dataInput.readUTF(); 

    dataInput.close(); 

    String[] values = param.split("%"); 
相關問題