【问题标题】:Transfering multiple parameters in the applet-servlet communication在 applet-servlet 通信中传输多个参数
【发布时间】:2011-05-19 02:48:30
【问题描述】:

我正在实现一个小程序---servlet 通信。有两个参数需要通过applet 发送到servlet。我不确定是否可以按如下方式实施转移过程?如果不是,如何处理涉及多个参数的传输处理?谢谢。

小程序方面:

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

【问题讨论】:

标签: java servlets applet


【解决方案1】:

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

小程序端:

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");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多