0

I am implementing an applet ---servlet communication. There are two parameters that need to be sent by applet to the servlet. I am not sure can I implement the transferring process as follows? If not, how to handle the transferring processing involving multiple parameters? Thanks.

Applet side:

// send data to the servlet
             URLConnection con = getServletConnection(hostName);
             OutputStream outstream = con.getOutputStream();
             System.out.println("Send the first parameter");
             ObjectOutputStream oos1 = new ObjectOutputStream(outstream);
             oos1.writeObject(parameter1);
             oos1.flush();
             oos1.close();

             System.out.println("Send the second parameter");
             ObjectOutputStream oos2 = new ObjectOutputStream(outstream);
             oos2.writeObject(parameter2);
             oos2.flush();
             oos2.close();

Servlet side:

    InputStream in1 = request.getInputStream();
    ObjectInputStream inputFromApplet = new ObjectInputStream(in1);
    String receievedData1 = (String)inputFromApplet.readObject();

    InputStream in2 = request.getInputStream();
    ObjectInputStream inputFromApplet = new ObjectInputStream(in2);
    String receievedData2 = (String)inputFromApplet.readObject();
bit-question
  • 3,463
  • 14
  • 44
  • 60
  • Have you looked at using the technique described [here](http://stackoverflow.com/questions/314300/how-to-simply-generate-post-http-request-from-java-to-do-the-file-upload)? – aroth May 19 '11 at 02:58
  • And here http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests – BalusC May 19 '11 at 03:06
  • don't close the ObjectOutputStream between parameters, just write both to the first ObjectOutputStream. – MeBigFatGuy May 19 '11 at 03:18

1 Answers1

1

For simplicity, you should use HTTP GET or POST parameters (since they are String values).

Applet side :

URL postURL = new URL("http://"+host+"/ServletPath");
HttpURLConnection conn = (HttpURLConnection) postURL.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.connect();

PrintWriter out = new PrintWriter(conn.getOutputStream());
out.write("param1="+URLEncoder.encode(parameter1)+"&param2="+URLEncoder.encode(parameter2));
out.flush();

The host can be obtain from getCodeBase().getHost() in you Applet instance.

Servlet Side :

void doPost(HttpServletRequest req, HttpServletResponse resp) {
    String parameter1 = req.getParameter("param1");
    String parameter2 = req.getParameter("param2");
}
h3xStream
  • 5,555
  • 2
  • 38
  • 50