2013-03-11 73 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("%"); 
相关问题