applet可以通過發送一個GET或者一個POST方法將數據發送到servlet。
一 GET方法
使用GET方法發送數據到servlet,applet必須將name/value 配對參數翻譯成為實際的URL字符串。例如要發送name/value配對信息"LastName=Jones",servlet URL如下:
http://www.foo.com/servlet/TestServlet?LastName=Jones
如果還有另外的配對信息,則用一個’&’符號將它們連接。方法如下:
http://www.foo.com/servlet/TestServlet?LastName=Jones&FirstName=Joe
在應用中,必須翻譯每一個按name/value配對的信息。為發送一個方法GET方法到servlet,applet用類java.net.URLConnection來實現。下面的代碼片段將實現:
String location = "http://www.foo.com/servlet/TestServlet?LastName=Jones";
URL testServlet = new URL(location);
URLConnection servletConnection = testServlet.openConnection();
inputStreamFromServlet = servletConnection.getInputStream();
// 從servlet讀input。
一旦applet建立了一個到URL的連接,這時訪問了來自servlet 的input stream。applet可以讀這個input stream從而處理此數據。依賴servlet返回此數據的類型和格式。如果servlet 正返回定制的信息,需要創建一個定制的消息傳輸協議來實現applet 和 servlet通信(交互)。
二、POST方法
使用POST方法發送數據到servlet,必須通知URL連接output stream發送數據。方法POST是很強大的,因為它可以發送任何形式的數據(諸如純文本,二進制碼之類)。您需要做的只是在HTTP 請求header中設置滿意的類型。但是,此servlet必須可以處理由applet發送的此類型的數據。
下面的代碼片段顯示了如何發送方法POST到一個servlet URL。
// 連接servlet
String location = "http://www.foo.com/servlet/TestServlet";
URL testServlet = new URL( servletLocation );
URLConnection servletConnection = testServlet.openConnection();
// 通知此連接我們將要發送output并且要接收input
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
servletConnection.setUseCaches (false);
servletConnection.setDefaultUseCaches (false);
// 指定我們將要發送的數據內容的類型為binary數據
servletConnection.setRequestProperty
("Content-Type", "$#@60;insert favorite mime type$#@62;");
// 從servlet上取得input和output streams
. . .
// 將您的數據發送到servlet
. . .