Communication between Applet and Servlet in enterprise applications

Source: Internet
Author: User
In today's multi-layered web application design, we can use both Java Applet and servlet. The applet provides a convenient mechanism for building a powerful dynamic interface. servlet provides an efficient means for Web servers or other application servers to process requests. Sun's application model describes the best specification for developing enterprise-level Java applications on the Java 2 platform. A recommended specification is to use the servlets and other components supported by enterprise ans on the frontend using applets, HTML, and JSP.
The key to this architecture is the communication between the client Applet and the server servlet. However, because the applet is restricted by the browser security mode, it is not as easy to access data and information in an applet. In this article, we will explain the limitations faced by developers in the applet-servlet structure, and discuss several different communication policies that can transfer data between the applet and servlet. If you are familiar with the applet and Servlet, this will certainly help you read this article. If you are not so familiar with it, it doesn't matter. We will briefly introduce them.

Introduction to Applet and Servlet
Applet
Java applets is actually a Java program running on the web page. It is a Java class inherited from Java. Applet. Applet. It is embedded into HTML pages through reference, just like an image. The combination of Applet and HTML allows you to build a more powerful dynamic interface. For some applets that only use to scroll the body and play the animation, we can use it in an enterprise-level application to display and process data from resources on the server. For example, an applet can be used to browse and modify records in the database or control other applications running on the server.
In addition to its own class files, Java Applet can also use other classes, whether they exist independently or are packaged into a jar file. The Applet and its class files are distributed through standard HTTP requests, so the applet can be sent across the firewall of the platform where web page data is located. Unless it involves maintaining the integrity of the application, the applet will automatically refresh each time the user re-accesses the web host and will be retained on the client for a period of time.
Thanks to the platform independence of the Java operating system, the applet can run on any browser with a Java Virtual Machine (JVM. Sun's Java Plug-in can even use the latest JVM version to compile pages without worrying about restrictions on the JVM version on your browser.
Because the applet is an extension of the Java platform, you can reuse existing Java components when creating a web application interface with the applet. As we can see in the following example, you can use complex Java objects in your applet components to develop the work originally completed by the server application. In fact, you can write such Java code, which can be executed on the applet or in the application.
Applet has all the functions of traditional Java applications, including using sun's jfc/swing components. Applets can also be used to create graphs and user interfaces in applications (although some auxiliary windows are marked as "Warning, Java Applet windows "). However, no matter how similar they are, there are still some key differences between applications and applets. For example, we have to consider that our applet is restricted by the security mode.

Applet security constraints
The applet code comes from the web host and runs in the browser of the end user's machine. Harmful viruses containing the applet may cause destructive effects. to prevent such an applet, the applet is restricted by security, that is, the applet can only communicate with the host that provides the applet, moreover, the applet cannot operate the end user's machine. They cannot read or write the user's file system, execute the above program, or check some sensitive environment parameters. (In fact, there is a way to circumvent this restriction, that is, developers can use the digital signature technology to mark the applet, which will ask users whether they can give the applet some special treatment. But this is beyond the scope discussed in this article .) In addition, the applet cannot establish or accept external socket connections. The external connection is beyond the host that provides the applet file (not the host that provides the HTML that references the applet ).
Because of this security restriction, we must adopt a special policy for communication with the applet. The only way to communicate is the network connection between the host that provides the applet and the host that provides the corresponding HTML.
Servlets
Java Servlet is a server component and has many similarities with CGI. It can process Web requests and return data or HTML. Servlet can access the database for computing and communicate with components such as Enterprise JavaBean. Unlike CGI programs, servlet is persistent, that is, it can continuously process requests as long as it is used as an example (these requests may occur at the same time ). Therefore, servlet is more efficient than CGI.
Servlet runs in a servlet engine, usually on a Web server or application server. Both Netscape Enterprise Server 4.0 and Netscape application server support the latest java servlet specification. Unlike applet, servlet is not restricted by security constraints. Because the servlet runs completely on the server, it has the performance allowed by all operating systems.
Servlet can be used to easily establish connections between clients such as Applet and web browser and the core of enterprise applications. For the client, the requests sent to the servlet are no different from other Web requests. The client accepts the returned information through a URL. As we can see, the returned information is not only HTML. In fact, we can send and accept any type of data through the HTML protocol.

Constructor
An enterprise-level application can use several methods to construct the applet and servlet. I will introduce three different constructor methods and compare their advantages and disadvantages.
The first method actually only uses the applet instead of the servlet, although the applet is restricted by their security mode, however, the applet can still use protocols such as JDBC and RMI to access backend information such as databases, LDAP directories, and Enterprise JavaBeans components. This construction method 1 is shown. Although this method looks very simple, it is not a good method, it will bring a lot of problems. First, this arrangement requires you to embed all the access information directly into your applet code. Database usernames, passwords, and server identifiers. All this information must be included in your applet code, so that end users may collect this information from class files. In addition, the database or any other system you access must be on the same server that provides the applet. This means that your server will have to bear both the burden of being a web server and a database server. In typical cases, your backend resources may be protected by the firewall, but in this case, this is impossible, because the applet running on the client must directly access your machine. Finally, if you want to use a web server cluster using this method, it is at least difficult if it is not impossible.
Figure 1. Application construction with a double Structure

A better way is to encapsulate the transactions that communicate with the backend resources into the servlet, while the applet is only used to process the front-end work. In this constructor, as shown in figure 2, Servlet overcomes the inherent security constraints of Applet and is used to control applet access to the enterprise information system and transaction logic. When the servlet receives a request, it will query information in the backend database, execute computing, process the acquisition of information representing the applet, and act on the information from the applet. One major improvement of this method is that the applet/servlet pair can be distributed in a cluster of backend Web servers, and all the communication with a shared database exists in the backend. In addition, Servlet design helps design modularization, abstract the backend of an application to process business logic, and improve design flexibility.
Figure 2. Application construction with a three-tier structure

If you build your application around Enterprise JavaBeans, Servlet becomes the middleware. The EJB component can be used to separate the business logic from the servlet and make it more abstract. In this case, an applet communicates with its servlet, And the servlet communicates with the EJB component. As shown in figure 3. Introducing a hierarchy of EJB components, Servlets, and front-end applets/html in application construction can provide us with maximum flexibility and performance. Even if you do this, you must attach the cost of complexity and cost.
Figure 3. Multi-layered application Construction

Communication Policy
If you use this structure: Use the applet on the front end and use the servlet on the back end, you will need to execute the communication between the applet and the servlet. Because the applet is restricted by the security mode of the browser, we do not have much choice when accessing data and information of an applet. As we mentioned earlier, we cannot read the file system of the client or run the client program. Because the applet is not running on the server, we cannot access the file system on the server. We can only establish a network connection to a service running on our host. In addition, do not forget that applications are published on a public Internet, and the firewall may restrict sessions sent from http to servlet or other web-server modules. In fact, because the applet itself is published over HTTP on the network, we must accurately grasp the communication policy.
Assume that the network connection between the client Applet and the server servlet is the only communication path we can use. We can exchange information in several ways. As you know, text streams can be distributed by servers over HTTP. However, you may not know that Java objects can be issued in this way. We will introduce in detail the use of HTTP text streams and HTTP object streams. In addition, we will briefly introduce the method of communication through socket. This method is particularly useful when an application requires two-way, continuous connection.
HTTP text stream
The simplest way for an applet to exchange information with a servlet is through an HTTP text stream. The Java URL and urlconnection types make it easy to read data from a URL, so you don't have to worry about socket and other complex issues related to network work. All we need is a server-side component, which can issue information through URL. This is why servlet is used here.
As an example, we want to monitor the total number of memories that can be used by the JVM of the server, and display it with a simple meter in an applet. First, we need to develop a servlet. when accessing this servlet through its url, we can return the information we need to draw the meter. The source code of this servlet is shown in Listing 1.
Listing 1
Import javax. servlet .*;
Import javax. servlet. http .*;
Public class showmemservlet extends httpservlet {
Public void doget (httpservletrequest req, httpservletresponse res)
Throws servletexception, ioexception {
Res. setcontenttype ("text/plain ");
Printwriter out = res. getwriter ();
Runtime RT = runtime. getruntime ();
Out. println (RT. freememory ());
Out. println (RT. totalmemory ());
}
}
This very simple servlet will respond to a GET request (directly through the browser or through our Applet as we will see below) and return two lines of text. The first line shows the remaining free space of the server's JVM, and the second line shows all available space of the JVM ).
To create an instrument in our applet, we only need to establish a connection to this servlet, encapsulate its inputstream into a datainputstream, read the two parameters, and convert them into numbers, and update our instruments. We can let our applet execute the runnable interface and run it in its own thread. Every second, we can run a method to update our meter. The code for the refresh () method is shown in Listing 2.
Listing 2
Private void refresh () throws malformedurlexception, ioexception {
URL url = new URL (getcodebase (), "/servlet/showmemservlet ");
Urlconnection con = URL. openconnection ();
Con. setusecaches (false );
Inputstream in = con. getinputstream ();
Datainputstream textstream;
Textstream = new datainputstream (in );
String line1 = textstream. Readline ();
String line2 = textstream. Readline ();
Double freemem = double. parsedouble (line1 );
Double totalmem = double. parsedouble (line2 );
Int usef8 = totalmem-freemem;
Int percentused = (INT) 100 * (usef8/totalmem );
Meter. setlength (percentused );
}
As you can see, the use of HTTP text streams is quite simple and straightforward. The applet establishes a connection to the servlet, reads the two rows returned by the applet, and processes them properly.
There is a major weakness in using a simple text stream to exchange data, that is, the applet does not directly understand the data information, but converts it into a useful format. In our example, converting a string to a number is not too complicated, but when we try to process a more complex data and object, the conversion will soon become uncontrollable. In fact, we can see below that we have a simple method to process these complex data.
HTTP object stream
This function is used when the hosts file is created. We can use this function and combine the technology known as "Object Sequence" To Transmit Complete Java objects from servlet to applet. Complex data can be easily transmitted without any parsing or interpretation.
Object Sequence allows us to encapsulate an object into a binary data stream, which can reach anywhere an outputstream can reach: a disk, screen, or in our example, connecting to an applet through an HTTP. The object sequence is supported by jvm1.1 and later versions. Therefore, some earlier versions of browsers do not support this function. However, sun's Java Plug-in can upgrade almost all browsers to support the final version of Java, so that it can support object sequences.
The method for using an HTTP object stream is almost the same as that for using an HTTP text stream. We establish a servlet URL Connection to our web host and read the returned data. Instead of encapsulating inputstream into datainputstream, we encapsulate it into objectinputstream. We can read the objects according to the appropriate type.
Listing 3 shows a piece of code we use to exchange an object, which is used to obtain information about the book (including the author, question, price, and other information) from the servlet ). You will notice that here we use objectoutputstream to replace printwriter in Listing 1. Its basic concepts are the same.
Listing 3
Public void doget (httpservletrequest req, httpservletresponse res)
Throws servletexception, ioexception {
Outputstream out;
Objectoutputstream objstream;
Out = res. getoutputstream ();
Objstream = new objectoutputstream (out );
Album album = fetchnextalbum ();
Out. writeobject (album );
}
This servlet generates a serialized version of the bibliography object, which can be received as a data stream from its fetchnextalbum () method. If you access this servlet through a Web browser, you will see a bunch of spam, because currently you can only process text but not binary data object sequences. Note that this object must execute the serializable interface to serialize it. In addition, any other object that references this object must also execute the serializable interface.
On the applet end, whenever you click the next button of the applet, you can use the getnextalbum () method (as shown in Listing 4) to obtain the bibliography object from the server. The applet queries this object and displays its data.
Listing 4
Private album getnextalbum () throws malformedurlexception, ioexception {
URL url = new URL (getcodebase (), "/servlet/albumservlet ");
Urlconnection con = URL. openconnection ();
Con. setusecaches (false );
Inputstream in = con. getinputstream ();
Objectinputstream objstream;
Objstream = new objectinputstream (in );
Album = (album) objstream. readobject ();
Return album;
}
As you can see, object stream provides us with a very simple way to exchange a complex set of information before the applet and servlet. Please note that what we are dealing with is not simply data but an object, so you can reuse this object between the client and the server. This makes our program more intelligent and prevents repeated logic processing.

Socket Connection
In addition, the communication policy of Applet and servlet is usually used to establish a socket connection between the two. This means that developers use socket connections to design and execute appropriate protocols to process communication between the two.
One major advantage of using socket is that the connection is continuous and bidirectional. An HTTP-based connection can only exchange information temporarily. If you want to constantly update the applet with new information, you must constantly create new HTTP connections. For a socket connection, you can build only one connection with the server to achieve continuous updates.
Of course, you may want to build a multi-threaded system, so that you can have several applets to contact the server at the same time. Note that using socket is sometimes not an appropriate method. Most firewalls do not allow communication through rare port numbers. However, in an internal Intranet, this is still a very useful technology.

Collaboration between Applet and Servlet
In this article, we discuss some useful strategies for creating an application that uses the applet at the front end and Servlet at the backend. The applet has only one unique communication path, but we can exchange information between the applet and Servlet in several ways. For simple data and information, we can use plain text for transmission. We can use object sequences to directly use the work of objects and other complex data structures. For some internal applications that require real-time two-way connection, we can use socket connection.
The policies recommended by Sun's application model are the same as those discussed here. Separating the transaction logic from the interface makes the application more flexible and easy to upgrade, so that the application is easier to design and maintain. However, this model does not allow your applet to directly access your enterprise data, which greatly reduces the complexity of your system and greatly improves the security of your system. The collaboration between Applet and Servlet will help to build a better application.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.