applet和servlet交互

Introduction

Java servlets provide a new and exciting method of developing server-side solutions. Servlets provide the features of traditional CGI scripts with the added benefits of efficiency and portability. Currently, major corporations are making the migration from CGI scripts to Java servlets. As a result, the demand for applet and servlet communication is on the rise.

This article is the third in a three-part series on Java servlets. In the Feb 98 issue of JDJ , I presented you with a 3-tier database application that used Java servlets. In this article, you will learn how to build a 3-tier database application that allows a Java applet to perform two-way communication with a Java servlet. I will focus on the concepts and techniques of applets communicating with servlets. The article will build on the 3-tier application presented in the previous article. However, if you are a newcomer and missed the previous article, don't worry because I'll give a review of the application.

Reviewing our Student Tracker Application

Our previous article presented a 3-tier database application that used Java servlets and the Java Database Connection (JDBC). The application allows a public speaker to keep track of students who attends her seminars. Students interact with the application by entering their contact information into an HTML form. Once the form is submitted then the Java servlet uses JDBC to store the student information in a database. Afterwards, an updated student list is generated by the servlet and returned as an HTML page to the user.

The application is partitioned into three tiers: user interface layer, the business rules layer and the data store layer. Figure 1 illustrates the three-tier design.

FIGURE 1: Three-tier design

The first tier is a web browser, which serves as our universal client. In the first phase of the application, an HTML front-end was used for user-input and displaying the database query results. The HTML approach was taken because it lowered the requirements of the client's web browser version. By taking this low-tech approach, the application was accessible to users who had browsers that were not Java 1.1 enabled.

The second tier of the application is implemented with a Web server capable of executing Java servlets. The Java servlet harnesses the power of JDBC to access the database to store/retrieve information as needed. A dynamic HTML page is generated by the servlet based on the database results.

The third tier is composed of our back-end database server. The database server stores the information that is used by the application. Thanks to the JDBC API, the servlet can access the database in a portable fashion by using the SQL call-level interface.

Developing an Applet Front-end

In order to enhance the student tracking system, we will develop an applet front-end. The students can now enter their contact information into a Java dialog box. Also, an updated student list is displayed in a Java list component. Figure 2 below shows the new applet front-end.

FIGURE 2: Student Tracker Applet

Applet-Servlet Communication with HTTP GET and POST

In the previous version, the HTML form was used to submit the student's data to the servlet. Accessing the form data on the server side was simple and straightforward. This was accomplished by calling the method HttpRequest.getParameter( "<form field name>") which is available in the Java Servlet API.

However, we are now using an applet front-end and we need a mechanism for the applet to communicate with the servlet. We need to capture the information a student enters and somehow pass this information to the servlet. Since servlets support the HTTP/CGI interface, we can communicate with the servlet over HTTP socket connections. The applet simply has to open a connection to the specified servlet URL. Once this connection is made, then the applet can get an output stream or input stream on the servlet.

The applet can send data to the applet by sending a GET or a POST method. If a GET method is used, then the applet must URL encode the name/value pair parameters into the actual URL string. For example, if we wanted to send the name/value pair of LastName=Jones, then our servlet URL would resemble:

http://www.foo.com/servlet/TestServlet?LastName=Jones

If you have additional name/value pairs, then they are separated by an ampersand (&). So, adding an additional name/value pair of FirstName=Joe, then our revised servlet URL would resemble:

http://www.foo.com/servlet/TestServlet?LastName=Jones&FirstName=Joe

In our application, we would have to URL encode each name/value pair for the student's contact information. To send a GET method to a servlet, the applet can use the java.net.URLConnection class. The code fragment below shows you how.

String location = "http://www.foo.com/servlet/TestServlet?LastName=Jones";
URL testServlet = new URL( location );
URLConnection servletConnection = testServlet.openConnection();
inputStreamFromServlet = servletConnection.getInputStream();

// Read the input from the servlet.
. . .

Once the applet has opened a connection to the URL, then the input stream from the servlet is accessed. The applet can read this input stream and process the data accordingly. The type and format of the data returned depends on the servlet. If the servlet is returning custom information, then the creation of a custom messaging protocol is needed for the applet and servlet to communicate. However, I will not get into the details of a custom protocol because I'll present an elegant solution later in the article.

To POST data to a servlet, the java.net.URLConnection class is used again. However, this time, we must inform the URL connection that we will send data over the output stream. The POST method is powerful because you can send any form of data (plain text, binary, etc). All you have to do is set the content type in the HTTP request header. However, the servlet must be able to handle the type of data that the applet sends.

The code fragment below shows how to send a POST method to a servlet URL. The details of transmitting the data are discussed later in the article.

// connect to the servlet
String location = "http://www.foo.com/servlet/TestServlet";
URL testServlet = new URL( servletLocation );
URLConnection servletConnection = testServlet.openConnection();

// inform the connection that we will send output and accept input
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);

// Don't use a cached version of URL connection.
servletConnection.setUseCaches (false);
servletConnection.setDefaultUseCaches (false);

// Specify the content type that we will send binary data
servletConnection.setRequestProperty
("Content-Type", "<insert favorite mime type>");

// get input and output streams on servlet
. . .

// send your data to the servlet
. . .

As you can see, applets can communicate with servlets using the GET and POST method. However, when the applet sends data using a GET method, then it must URL encode each name/value pair.

Communicating w/ Object Serialization

In our application, we would like to provide a higher level of abstraction. Instead of passing each parameter of student information (i.e. last name, first name) as name value pairs, we would like to send it as a true Java object. Our Java application already has a Student class that encapsulates all of the information about a student (see Listing 1 ). This information is gathered from the New Student dialog box and a Student object is created. When we register a new student, we would like to simply send the Student object to the servlet. Upon receipt of the Student object, the servlet would add the new student to the database. Also, it is our desire for the servlet to send the applet an updated student list as a vector of student objects. This will allow the applet to quickly and easily display the student list.

How can we accomplish this you ask? Easy, thanks to Java's object serialization. Java 1.1 introduced object serialization, which allows an object to be flattened and saved as a binary file. The values of the data members are saved so in fact, the state of the object is persisted or serialized. At a later time, the object can be loaded or deserialized from the binary file with the values of its data members intact. Object serialization is fascinating in that it frees the developer from low-level details of saving and restoring the object.

You may wonder how does this relate to applet-servlet communication? Well, object serialization is not limited to binary disk files. Objects can also be serialized to any output stream. This even includes an output stream based on a socket connection. So, you can serialize an object over a socket output stream! As you've probably guessed by now, a Java object can also be deserialized or loaded from a socket input stream.

In order for a Java object to be serializable, its class must implement the java . io . Serializable interface. However, you will not have to actually implement any methods for this interface because the interface is empty. The java . io . Serializable interface is simply a tag for the Java Virtual Machine. We can create a custom class as follows:

class Foo implements java.io.Serializable
{
// normal declaration of data members,
// constructors and methods
}

The code fragment below shows you how to serialize an object to an output stream. In this example, we already have a socket connection to a host machine and we are simply serializing the object, myFoo .

outputToHost = new ObjectOutputStream(hostConnection.getOutputStream());

// serialize the object
Foo myFoo = new Foo();
outputToHost.writeObject(myFoo);
outputToHost.flush();
outputToHost.close();

Notice in the example that an ObjectOutputStream is created. This class is responsible for serializing an object. The object is actually serialized when the writeObject() method is called with the target object as its parameter. At this time, a binary image of the object is written to the output stream. In this case, the output stream is based on a socket connection.

However, this example would not be complete without code on the host machine to read the serialized object. The code fragment below shows you how to deserialize an object from an input stream.

inputFromClient = new ObjectInputStream(clientConnection.getInputStream());

// deserialize the object, note the cast
Foo theData = (Foo) inputFromClient.readObject();
inputFromClient.close();

An ObjectInputStream is created based on the client's socket connection. The object is deserialized by simply calling the readObject () method. However, we must cast the object to its appropriate class, in this case, the class Foo . At this point, the object is available for normal use.

As you can see, object serialization is very straightforward and easy. Now, we'll use this technology to pass objects back and forth between our applet and servlet.

Sending Objects from an Applet to a Servlet

With the information presented so far, we can send a Java object to a servlet. In our Student Tracking application, the applet sends a Student object to the servlet when a new student is registered. Figure 3 displays the object interaction between the servlet and the applet.

FIGURE 3: Applet-Servlet Object Transactions

The code fragment shown in Listing 2 is used by the applet to send the Student object to the servlet. The applet is actually sending a POST method to the servlet. This client-side code fragment opens a URL connection to the servlet URL. We inform the servlet connection that we are sending output data over the connection and receiving input. Methods are also called such that the connection will not use cached versions of the URL. An important call in this code fragment is setRequestProperty (…). This method sets the content-type in the HTTP request header to the MIME-type application/octet-stream. The application/octet-stream MIME-type allows us to send binary data. In our case, the binary data is our serialized Student object. The next couple of statements creates an ObjectOutputStream and actually writes the object to the connection stream.

However, we are not yet finished. Recall that our application is in the process of registering a new student. The servlet must read this student object and update the database accordingly. Thus, we need code on the server side to receive a serialized Student object.

The code fragment in Listing 3 displays the servlet code for reading a Student object from an applet. The servlet handles POST methods by implementing the doPost () method. The servlet acquires an ObjectInputStream from the requesting applet. From there, it is simply a matter of reading the Student object from the stream. At this point, the Student object is loaded and available for registration in the database. Please make note of the small number of statements on the server-side for reading in a serialized object. You must agree that it is quite simple and straightforward.

Sending Objects from a Servlet to an Applet

In our Student Tracking application, the servlet is now capable of receiving a student object and registering them in the database. Now, the servlet must return an updated list of registered students. The updated student list is returned as a vector of student objects. This interaction is also illustrated in Figure 3 .

When the servlet returns the vector of student objects, there is no need to iterate through the vector and serialize each Student object individually. The servlet can simply serialize the entire vector in one step, since the class java.util.Vector also implements the java.io.Serializable interface.

The code fragment shown in Listing 4 is used by the servlet to send a vector of Student objects to the applet. The sendStudentList () method is passed an HttpResponse parameter and a vector of Student objects. Since the applet initiated the HttpRequest , the servlet can respond to the applet by using the HttpResponse parameter. Thus, an ObjectOutputStream to the applet is created based on the HttpResponse object. The student vector is actually serialized and sent to the vector with a call to outputToApplet . writeObject ( studentVector ).

As we've seen before, code is needed by the applet to handle the data being sent from the servlet. The code fragment shown in Listing 5 is used by the applet to read in a vector the Student objects from the servlet. The applet opens a URL connection to the servlet's location. The necessary methods are called to ensure that the applet doesn't use cached versions of the URL connection. Next, an ObjectInputStream is created based on the servlet's input stream socket connection. Now, all of switches have been flipped and we can easily read in our vector of Student objects. Again, remember we have to cast the object to the appropriate type. Congratulations, you have successfully read in a vector of student objects. This vector is now available for refreshing the AWT List component.

Conclusion

This article went beyond the normal method of sending name/value pairs over the HTTP/CGI protocol. The techniques presented leveraged the features of Java object serialization. As you can see, this provided an elegant way of transmitting serialized Java objects over network connections.

However, I must inform you, this article only discussed communication using the HTTP/CGI protocol. There are a number of other mechanisms for applets to communicate with server-side processes. The first one that comes to mind is Java's Remote Method Invocation (RMI).

RMI allows a client application to call methods on a remote object as if the object was local. In fact, RMI uses object serialization to pass objects back and forth between the client application and the remote object. All of the low-level details of network connections and serialization are hidden from the developer when using RMI. If your project requires a large amount of applet-servlet communication, I'd recommend that you take a close look at RMI and the features it has to offer.

The second mechanism of communicating with server-side process is CORBA (Common Object Request Broker Architecture). Like RMI, CORBA allows you to make method calls on remote objects. If you have legacy server-side code written in a different language, then you can wrap it as a CORBA object and expose its functionality. CORBA provides a rich framework of services and facilities for distributing objects on the network.

If you'd like to get further information on distributed computing with RMI and CORBA visit the web-sites listed at the end of this article.

By now, you should understand the concepts and techniques for communication between applets and servlets. In this article, I demonstrated how an applet uses a POST method to send a serialized object to a servlet. The appropriate server-side code for the servlet was provided for reading in a serialized object. Our Student Tracking applet used this communication method to send a true Java object to a servlet. The servlet was also enhanced to return a vector of student objects to the applet. Likewise, the appropriate applet code was provided for reading in a vector of student objects.

As you can see, applet and servlet communication is straightforward with the techniques presented in this article. You can now add an applet front-end to your servlet-based application.

URL References:
Author By-Line

Chád (shod) Darby is a Java consultant for J9 Consulting, www.j-nine.com . He specializes in developing server-side Java applications and database applications. Chád received a B.S. in Computer Science from Carnegie Mellon University . You can reach him at darby@j-nine.com .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值