1

アプレットから、MySQL データベースに接続して転送されたデータを保存する特定のサーブレットにデータを送信したいと考えています。アプレット側では、次のメソッドを使用してアプレットからサーブレットにデータを転送しました。

  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 が私のセルベットのパスか。サーブレット側では、次のコードを書きました。

    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 リンクから直接呼び出すと、サーブレットは正常に動作し、問題なくデータベースを埋めることができますが、アプレットから呼び出すと、何も起こらず、例外もありません! 正直なところ、彼らはお互いにコミュニケーションを取ることができず、私は本当に混乱しています.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();

サーブレット側:

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

    dataInput.close();

    String[] values = param.split("%");
于 2013-03-13T20:17:08.673 に答える