jsp教程servlet與applet的交互 Applet與Java Servlet可以通過HTTP協議的GET和POST進行交互,Applet必須打開一個到指定的servlet URL的連接.一旦建立了此連接,applet就可以從servlet得到一個output stream或者一個input stream.
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);
< /不能使用URL connection的緩存.
servletConnection.setUseCaches (false);
servletConnection.setDefaultUseCaches (false);
// 指定我們將要發送的數據內容的類型為binary數據
servletConnection.setRequestProperty
("Content-Type", "$#@60;insert favorite mime type$#@62;");
// 從servlet上取得input和output streams
. . .
// 將您的數據發送到servlet
. . .
[火星人 ] jsp教程servlet與applet的交互已經有622次圍觀