在applet-servlet通信中传输多个参数

时间:2011-05-19 02:48:31

标签: java servlets applet

我正在实现一个applet --- servlet通信。 applet需要将两个参数发送到servlet。我不确定如何实施转移流程如下?如果没有,如何处理涉及多个参数的传输处理?感谢。

Applet方面:

// 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方:

    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();

1 个答案:

答案 0 :(得分:1)

为简单起见,您应该使用HTTP GET POST 参数(因为它们是字符串值)。

Applet方面:

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();

可以从Applet实例中的getCodeBase().getHost()获取主机。

Servlet方:

void doPost(HttpServletRequest req, HttpServletResponse resp) {
    String parameter1 = req.getParameter("param1");
    String parameter2 = req.getParameter("param2");
}