1

我想将一些数据从我的 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()调用_ 当我直接从其 http 链接调用 Servlet 并毫无问题地填充数据库时,Servlet 可以正常工作,但是当我从 applet 调用它时,什么也没有发生,甚至没有任何异常!老实说,他们无法相互交流,我真的很困惑。doGet()doPost()

4

1 回答 1

0

我最终使用此代码发送了多个参数:(这只是一个建议,也许还有更好的解决方案,但它对我有用)

小程序方面:

    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("%");
于 2013-03-13T20:17:08.673 回答