Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
17.3 Sending Data with GET and Processing the Results Directly
441
Reading Serialized Data Structures
The approach shown in the previous subsection makes good sense when
your applet is talking to an arbitrary server side program or reading the
content of static Web pages. However, when an applet talks to a servlet,
you can do even better. Rather than sending binary or ASCII data, the
servlet can transmit arbitrary data structures by using the Java serialization
mechanism. The applet can read this data in a single step by using
readOb
ject
; no long and tedious parsing is required. The steps required to imple
ment HTTP tunneling are summarized below. Again, note that the
statements need to be enclosed within a
try
/
catch
block in your actual
applet.
The Client Side
An applet needs to perform the following seven steps to read serialized data
structures sent by a servlet. Only Steps 5 and 6 differ from what is required to
read ASCII data. These steps are slightly simplified by the omission of the
try
/
catch
blocks.
1. Create a
URL
object referring to the applet's home host.
As before, since the URL must refer to the host from which the
applet was loaded, it makes the most sense to specify a URL
suffix and construct the rest of the URL automatically.
URL currentPage = getCodeBase();
String protocol = currentPage.getProtocol();
String host = currentPage.getHost();
int port = currentPage.getPort();
String urlSuffix = "/servlet/SomeServlet";
URL dataURL = new URL(protocol, host, port, urlSuffix);
2. Create a
URLConnection
object. The
openConnection
method of
URL
returns a
URLConnection
object. This object
will be used to obtain streams with which to communicate.
URLConnection connection = dataURL.openConnection();
3. Instruct the browser not to cache the URL data. The first
thing you do with the
URLConnection
object is to specify that
the browser not cache it. This guarantees that you get a fresh
result each time.
connection.setUseCaches(false);
Home page for this book: www.coreservlets.com; Home page for sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved