我的applet无法连接到Servlet并传输数据

时间:2013-03-11 18:14:20

标签: java mysql servlets applet httpurlconnection

我想将我的Applet中的一些数据发送到一个特定的Servlet,该Servlet应该连接到MySQL数据库并存储传输的数据。 在Applet方面,我使用此方法将数据从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方面,我写了这段代码:

    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()doGet()的{​​{1}}次来电。 当我直接从它的http链接调用它并且没有任何问题填充数据库时,Servlet正常工作,但是当我从applet调用它时,没有任何反应,甚至没有任何异常!说实话,他们不能互相沟通,我真的很困惑。

1 个答案:

答案 0 :(得分: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("%");