Sie sind auf Seite 1von 34

Advanced Programming Using Java

Distributed Programming with Java

Distributed Programming with Java


At the end of this chapter you will be able to design distributed applications in Java using Javas distributed Object model. You will be able to design distributed applications using RMI and Servlets.

SCOPE
6.1 Distributed Application Design 6.1.1 Distributed Programming on Internet and Intranets 6.1.2 Distributed Computing Environment (DCE) 6.1.3 Distributed Component Object Model (DCOM) 6.1.4 Common Object Request Broker Architecture (CORBA) 6.1.5 Remote Method Invocation (RMI) 6.2 Java Distributed Object Model 6.2.1 Advantages 6.2.2 Disadvantages

6.3 Servlets 6.3.1 History 6.3.2 Introduction to Java Servlets 6.3.3 Java Servlet API 6.3.4 Creating a Servlet 6.3.5 Handling HEAD requests 6.3.6 init() method 6.3.7 Some important Servlet Methods 6.3.8 Communication between Applets and Servlets

Advanced Programming Using Java

Distributed Programming with Java

6.1 Distributed Application Design


Most of the development and deployment environments today are networked. Therefore it becomes necessary for the applications that are designed to be distributed. Distributed applications are able to concurrently server many users. In a distributed application, the processing is distributed across multiple networked computers. Distributed applications are mostly implemented as client/server systems. In a client/server system, the client requests the server for some resource. The server then accepts that request, processes it and gives the result back to the client. There are typically three components in a client/server system the user interface layer, the information processing layer, and the information storage layer. The user interface layer is implemented by the application client. Web Browser is an example of the user interface component of the distributed applications. The information processing layer is implemented by the application client or the application server or an application server support. For example, consider a distributed application that builds a query at runtime by asking for the column names from the user. The browser can ask for the columns/table to be queried and thus implements the user interface layer. Then this database application may use a database client to convert the values entered by the user into an equivalent SQL statement. This database client can reside on either the client or server machine. The information storage layer is implemented by the database servers, e.g., Web Servers, FTP Servers, File Servers, etc. Fig. 6.1 and 6.2 shows these three layers with respect to the database application. Fig. 6.1 shows the information processing layer being implemented at the client machine and fig. 6.2 shows the information processing layer being implemented at the server machine.
Client Machine Server Machine

User Interface Layer (Browser)

Information Processing Layer (Application Client)

Information Storage Layer (Application Server)

Fig. 6.1 The components of a distributed application with Information Processing Layer at the Client machine

Advanced Programming Using Java

Distributed Programming with Java

Client Machine

Server Machine

User Interface Layer (Browser)

Information Processing Layer (Application Client)

Information Storage Layer (Application Server)

Fig. 6.2 The components of a distributed application with Information Processing Layer at the Server machine

6.1.1

Distributed Programming on Internet and Intranets

Internet is the most popular network today. Today almost all transactions happen on the net. This requires the applications over the net to be distributed as well. On the net a client program is executed on multiple host computers. The client interacts with the server with the help of TCP/IP protocol. The server listens for the incoming requests on a well-known port. The server uses gateway programs or back-end servers to process the requests. Most of the environments today are at least Intranet aware. Intranet is the Internet that is organization wide. In the case of Intranets, applets are used in a web browser to interact with the Web server. The Web Server in turn can use Database server or File server to process the client requests. The approach used in Intranets is the client/server approach, but this approach can be used with Internet applications also. 6.1.2 Distributed Computing Environment (DCE)

The OSFs (Open Software Foundation) DCE (Distributed Computing Environment) is an industry-standard, vendor-neutral set of distributed computing technologies. It provides security services to protect and control access to data, name services that make it easy to find distributed resources, and a highly scalable model for organizing widely scattered users, services, and data. DCE runs on all major computing platforms and is designed to support distributed applications in heterogeneous hardware and software environments. DCE is a key technology in three of today's most important areas of computing: security, the World Wide Web, and distributed objects. Distributed systems are organized into cells. A cell is nothing but a group of processing resources, services, and users, that support a common function and share a common set of DCE services. For example, cells can be organized according to the departments in a company so that there is a different cell for finance, marketing, and manufacturing departments.

Advanced Programming Using Java

Distributed Programming with Java

DCE comprises of services that reside on top of the operating system, forming middleware that allows organizations to distribute processing components and data across the enterprise. Middleware such as DCE insulates developers from the complexities of the underlying network and its transport mechanisms, and provides an environment that allows key services (such as security and naming) to be integrated into distributed applications. The services and technologies used within a DCE cell consist of the following: Directory Service Stores the name of the resources. Cell Directory Service or CDS supports naming within a cell and Global Directory Service or GDS supports naming across all cells. Distributed File Service (DFS) This service is optional and it provides seamless file system that operates across all computers within a cell. Distributed Time Service (DTS) This service is used to synchronize time across all computers in a cell. Security Service This service is used for authentication purposes and for controlling access across all computers in a cell. Remote Procedure Calls (RPC) RPC is implemented as a layer built on the top of TCP/IP transport layer and transparently performs connection management. It replaces TCP sockets as the basic mechanism for client/server communication. DCE Threads DCE threads are similar to Java threads. Because DCE is independent of the operating system and network, it enables interaction between clients and servers in virtually any type of environment an organization may have in place. 6.1.3 Distributed Component Object Model (DCOM)

DCOM (Distributed Component Object Model) is a product by Microsoft and is used for developing distributed applications. DCOM has a long history attached to it. DCOM is essentially distributed COM. Therefore, to understand DCOM let us first see what is COM. It all started with OLE (Object Linking and Embedding) technology that was used to support compound documents. A compound document is one that is a product of multiple applications. COM was a solution to early problems in OLE. COM is different from DCE in its design approach. DCE is procedure-oriented whereas COM is object-oriented. Note that COM is not a language but a model on which applications can be built. Thus any programming language can be used with COM to create distributed applications. COM objects are instances of classes and are organized into interfaces. An interface is a collection of methods. The best thing about COM is that it abstracts the user away from the implementation details and presents a common interface to all objects, but the objects could be implemented in different ways. COM library is the key to implementing this common interface between objects. This library provides a directory of all classes that are available on the system. When one COM object invokes another COM object, it first invokes the functions in the COM library. These functions are used to either create a COM object from its class or get a pointer to its interfaces. COM runtime process helps the COM library in implementing its functions.

Advanced Programming Using Java

Distributed Programming with Java

DCOM is nothing but distributed COM over multiple computers. It allows a COM object on one computer to access methods of another COM object on some other machine. DCOM makes this access mechanism transparent to the user. A remote object is accessed in exactly the same manner as the local object. The remote objects class must be registered in the local registry of the local system for a local object to access the methods of that remote object. The DCOM also works in the same way as the COM object with the only difference being that the remote object resides on some other machine. The local object invokes the methods of local COM library of the remote object it is trying to access. The COM library processes these function calls using local COM Runtime. The local COM Runtime gets in touch with COM Runtime of the remote machine and requests the creation of remote object or invocation of its method. If the request is acceptable to the remote system security, the request is processed by COM Runtime. Both of the COM Runtime communicate with each other using Object RPC mechanism. The most important feature of the DCOM is its support for application security. Its security is based on Windows NT security policy. Thus, one can permit what all methods of an object can be accessed by a user or by another object. Also there are a variety of encryption mechanisms that can be used to protect information when it is transferred from one machine to another. However, the biggest drawback of DCOM is that it gives good performance on Windows platform but mediocre performance on all the other platforms. 6.1.4 Common Object Request Broker Architecture (CORBA)

CORBA (Common Object Request Broker Architecture) is the most popular architecture for building distributed object-oriented applications. The factors that make it so popular are that it is an open standard, is not tied to a particular vendor, and thus, is most widely used. In CORBA, objects are accessible via Object Request Brokers (ORBs). This means that an object can access another objects methods via an ORB. The clients interface to ORB is written in IDL (Interface Definition Language), and is known as IDL stub. IDL provides a programming language-independent mechanism for describing the methods of an object. The server interface to ORB is known as IDL skeleton. The client object invokes the methods of the IDL stub corresponding to the remote object. The IDL stub passes these invocations to the ORB. The ORB in turn invokes the corresponding methods of the IDL skeleton. IDL skeleton invokes the methods of the server object implementation. The server object returns the result back to the IDL skeleton, which in turn passes them back to the IDL stub via ORB. The IDL stub then communicates the results back to the client object. This remote method invocation is depicted pictorially in fig. 6.3.

Advanced Programming Using Java

Distributed Programming with Java

Client Host Client Object

Server Host Server Object

IDL Stub

IDL Skeleton

ORB

Fig. 6.3 Method Invocation in CORBA

There are many factors in favour of CORBA that makes it the most widely used model for developing object-oriented distributed applications. The first and the most important thing is that it is an open standard and works on all platforms. Instead of having the earlier client/server approach where browsers were clients and web servers were servers, both clients and servers can be distributed in CORBA. CORBA implementation is language-independent. You just have to provide IDL interface to the object and the object can be written in any language. It is an international standard and is recognized by most of the software vendors. 6.1.5 Remote Method Invocation (RMI)

Now that you are familiar with various approaches that are used to develop distributed applications, you must be wondering why Java did not pick of any one of these services for method invocations. JavaSoft found that every approach had some or the other drawback in it and thus, there was a need of a mechanism that provides the capability to develop pure Java distributed applications. TCP sockets can be used for remote method invocations and Java supports them too. But developing these sockets is a big overhead. JavaSoft decided that the need was to design a low-overhead mechanism for distributed applications that would be something like CORBA. DCE is also used for designing distributed applications, but DCE is procedureoriented. Its RPC does not gel with Javas object-oriented distributed applications. DCOM is again a very popular product, but as mentioned in section 6.1.3, it does not give good performance on platforms other than Windows. Also, DCOM does not support Java objects fully. CORBA is an excellent approach and JavaSoft would have adopted it but for its IDL. A Java programmer will have to learn IDL to be able to develop distributed Java applications.

RMI (Remote Method Invocation) is JavSofts answer to designing object-oriented distributed pure Java applications. Javas RMI is developed on the same lines as

Advanced Programming Using Java

Distributed Programming with Java

CORBA. Here also you need a client stub and a server skeleton that act as the interface to the client object and server object respectively. The goals for supporting distributed objects in the Java language are: Support seamless remote invocation on objects in different virtual machines. Support callbacks from servers to applets. Integrate the distributed object model into the Java language in a natural way while retaining most of the Java language's object semantics. Make differences between the distributed object model and local Java object model apparent. Make writing reliable distributed applications as simple as possible. Preserve the type-safety provided by the Java runtime environment. Various reference semantics for remote objects; for example live (nonpersistent) references, persistent references, and lazy activation. The safe Java environment provided by security managers and class loaders. But before talking about how RMI applications are designed, let us first see the architecture of RMI or the Java Distributed Object Model in detail.

6.2 Java Distributed Object Model


Javas distributed object model is simply an extension of Javas object model. In Javas object model, objects interact with each other within the same JVM whereas in Javas distributed object model, an object residing in a JVM can interact with an object in another JVM. The object that is trying to invoke the methods is known as the client object or the local object and the object whose methods are being invoked is known as the server object or the remote object. In Javas distributed object model, a local object does not reference the remote object directly. Instead it references a remote interface that is implemented by the remote object. There are many advantages of using remote interface, which are as follows: Remote interface allows server objects to differentiate between their local and remote interfaces (an object can provide methods via its remote interface other than its own methods). Use of remote interfaces present different access modes, e.g., remote administration interface can be used by the client that wants to use the administrative services of a remote object, and remote user interface can be used by the client that wants to access the normal services of remote object. Since remote interface is present, there is no need to have the server class file at the time of compilation of client objects. Java RMI follows a three tiered architecture that is quite similar to CORBA. Like CORBA there are stub classes and skeleton classes that reside on client and server respectively. In Java RMI, the client object invokes the methods of stub class (the same way as it is done in CORBA). But the only missing thing here is the ORB. Java uses Remote Reference Layer for communication between the stub and the skeleton. The remote reference layer sets up a connection between the address spaces of local and remote machine and obtains a reference to the remote object. If the stub communicates with more than one instances of skeleton, the mode of communication is said to be multicast. Multicast is not yet supported by Java. Java only supports unicast communication currently. The remote reference layer on the client

Advanced Programming Using Java

Distributed Programming with Java

machine communicates with the remote reference layer on the server machine via the transport layer. The transport layer is responsible for managing connections between the two machines. It uses TCP sockets to do so by default, but it can be configured to support other protocols too like SSL (Secure Socket layer) and UDP. Fig. 6.4 shows the threetiered architecture of Java RMI pictorially.

Client Object

Server Object

Stub

Skeleton

Remote Reference Layer

Remote Reference Layer

Transport Layer

Transport Layer

Lower Layer Protocols

Lower Layer Protocols

Fig. 6.4 Three tier architecture of Java RMI

In RMI, the remote object must be registered with the remote registry (Remote registry is a process that is created by running the rmiregistry program). This is done by associating its object instance with a name. When a client tries to access the remote object, the transport layer on the local host communicates with the transport layer of the remote host to find out if the referenced object exists. This information is accessed by the server host with the help of remote registry. If a client object has to send arguments to the remote objects method, the type of the argument must be Serializable. If both client and the server hosts reside within the same JVM, the object is passed by reference and if they reside in different JVMs, the object is copied from the client machine to the server machine. The same thing applies when an object is returned by the server to the client. 6.2.1 Advantages

Java RMI is a great option for Internet programming. There are many advantages of using Java RMI for communication between applets and server applications. Some of these advantages are: Java RMI is a part of JDK 1.1 as well as JDK 1.2, and thus an RMI applet will be supported by every JDK 1.1 and 1.2 compatible client. As a result, you dont have to worry about creating your own communication classes and packaging them with the applet.

Advanced Programming Using Java

Distributed Programming with Java

An executable version of RMI registry is available in Java 1.1 and 1.2 runtime packages. Thus, you are able to deploy your server applications without needing an expensive application server. RMI can also tunnel its transaction through HTTP, if necessary. This allows the users who are connected to the Internet through an HTTP proxy server to use RMI applets. It is very simple to write code for a distributed application since applet can execute server-side operations with simple function calls. Disadvantages

6.2.2

Despite having many advantages, Java RMI is still not so popular for developing distributed applications. This is because RMI applets have many limitations. These limitations are given below: The most popular browsers like Internet Explorer and Netscape Navigator do not support RMI fully. Navigator does support RMI on most of the platforms but does not support HTTP tunnelling, as a result, the Internet users connected through a proxy server are not able to use RMI applets. Netscape does not support RMI on the Macintosh platform at all. While accepting the connections on the Internet, RMI registry experiences some problem that requires the registry to be shut down and started again. In environments prior to Java 1.2.2, server sockets that handle the connections from RMI clients can live on indefinitely even after the clients have shut down. RMI registry allows client connections to be made for only one specific hostname. This means that server application cannot support multiple domains on a single web server, which limits the deployment options. Data that is exchanged on the net need to be encrypted and compressed by many applications. RMI makes it possible to do such a thing very easily by creating your own socket classes and an RMI socket factory. But overriding RMI socket factory disables its ability to do HTTP tunnelling which prevents the users that are connected to Internet via a proxy server to access RMI applets.

6.3 Servlet
Till now we have seen how Java can be used to create client side applications and also applets that can run on Internet. But even applets belong to the client side. In RMI, we did have a fair amount of idea how Java applications can be used at server-side. Servlets are another extension to server-side applications. Servlets are server-side Java applications that can be loaded dynamically. But before talking about Servlets, let us look at the history of server-side applications. 6.4.1 History

A Web Server generally has to handle a large amount of requests concurrently and thus it is not able to handle all transactions that keep coming in. For this purpose, some applications are used to extend the web servers. The oldest in this category are CGI (Common Gateway Interface) scripts. CGI was, in fact, the first technique to be used to

Advanced Programming Using Java

Distributed Programming with Java

create dynamic content. This revolutionized the way requests were handled by web servers since dynamic contents could be sent now instead of a static file. However, like any other technique this too has many drawbacks. CGI runs as an external application, this means that CGI scripts cannot interact with the web server or take advantage of its capabilities. This is because it is running as a separate process. Secondly, for each request that a server receives for a CGI program, it starts a separate process. Then the server passes all the data that the CGI program might need to generate the response with the help of environmental variables and standard input. This limits the number of requests a server can handle. To make the matters worse, if Perl language is used with CGI (which is the predominant choice for CGI script writers), it requires a Perl interpreter to be started for each request. This takes more time and extra resources. Fig. 6.9 shows the working of a CGI-based web server.

Call for CGI A Call for CGI B Call for CGI A Server

Process for CGI A Process for CGI B Process for CGI A

Fig. 6.9 A CGI based Server

FastCGI was developed as an alternative to CGI. This creates a single persistent object for each FastCGI program. FastCGI had many advantages over CGI but there are still many problems with FastCGI. In case of concurrent request, the FastCGI program need to have a pool of processes and for each process, a Perl interpreter. For this reason most of the web servers are not using FastCGI technique. Fig. 6.10 shows the working of a FastCGI based server.

Call for FastCGI A Call for FastCGI B Call for FastCGI A Server

Process for FastCGI A Process for FastCGI B

Fig. 6.10 a FastCGI based Server

Apart from CGI/Perl, there are many other technologies that can be used to create
Server Call for Server Extension A Call for Server Extension B Call for Server Extension A Server Extension A Server Extension B

Advanced Programming Using Java

Distributed Programming with Java

dynamic content like ASP, JavaScript, etc. Then several companies have also introduced server extension APIs for their web servers. For example, Netscape provides an API known as NSAPI, and Microsoft provides an API known as ISAPI. One can write server extensions using these APIs. These server extensions can make full use of servers resources and can run extremely fast but they pose some severe security and reliability hazards. A crashed server extension can bring the entire network down. In contrast to CGI and FastCGI, the server extensions run as a part of server only. Fig. 6.11 shows the working of server extensions.
Fig. 6.11 Server Extension API used with web server

Apart from server extension APIs, there are techniques like ASP and server-side Java Script that can be used to create dynamic content. ASP or Active Server Pages is a product by Microsoft that allows snippets of code to be embedded in an html document. This code is read and executed by the web server before it sends the page to the client. Server-side JavaScript is a technique by Netscape which, like ASP, allows snippets of code to be embedded in an html document. 6.4.2 Introduction to Java Servlets

Java Servlets are nothing but server-side Java programs that can be loaded dynamically. A Servlet is very similar to CGI or a server extension in functionality with the difference being that it runs inside a JVM on the server, and therefore, is safe and portable. Servlets, unlike applets do not require a browser to run, they run within the domain of server. The major drawback in CGI and FastCGI technique is that they run multiple processes to handle different requests. A Servlet, on the other hand handles each request using Javas multithreading capability. It creates a separate thread to handle each request (refer to fig. 6.12).
Server
JVM

Call for Servlet A Call for Servlet B Call for Servlet A

Servlet A Servlet B

Fig. 6.12 Servlet based web server

As a result servlets become more efficient and scalable. Another advantage of servlets is that they are portable across operating systems and web servers. Most of the web servers support servlets. Though servlets are basically used in place of CGI scripts, they can be used to extend any type of server like FTP server, mail server, etc. Most of the web servers do not have support for the servlets built into them since servlets are a fairly new concept. One can use add-on servlet engines on top of web servers for the

Advanced Programming Using Java

Distributed Programming with Java

web servers to support servlets. For example, one can use IBMs WebSphere with Microsofts Internet Information Server (IIS). 6.4.3 Java Servlet API

The Java Servlet API is not a part of JDK, you have to install JSDK (Java Servlet Developers Kit) separately. The Java Servlet API consist of two packages javax.servlet and javax.servlet.http. The javax.servlet package is used to create proptocol-independent servlets. The javax.servlet.http package is used to create HTTP servlets. All servlets must implement Servlet interface. A protocol independent servlet can extend the class javax.servlet.GenericServlet (this class Servlet interface) and an HTTP servlet can extend implements javax.servlet.http.HttpServlet class. HttpServlet class is a subclass of GenericServlet class. A servlet works via the request-response cycle. A request is sent to the servlet by the client, the servlet processes it, generates a response and sends the response back to the client. In a protocol independent servlet, the request is handled by its service() method. The service() method accepts two parameters a ServletRequest and a ServletResponse type objects. The ServletRequest object specifies the clients request and the ServletResponse object specifies the response of the servlet to that request. An HttpServlet, on the other hand, does not usually overrides the service() method. This is because it has specific methods called doGet() and doPost() to handle specific requests. The service() method in turn dispatches requests to these methods. Both doPost() and doGet() methods accepts two arguments an HttpServletRequest object and an HttpServletResponse object, which again specifies the request and response respectively. The doPost() method corresponds to the POST method of HTTP protocol and doGet() method corresponds to the GET method of HTTP protocol. The HttpServlet's service() method, by default, also calls the doOptions() method when it receives an OPTIONS request, and doTrace()when it receives a TRACE request. The default implementation of doOptions() automatically determines what HTTP options are supported and returns that information. The default implementation of doTrace() causes a response with a message containing all of the headers sent in the trace request. These methods are not typically overridden. The doHead() method is used to access header information of a request. The doPut() method is used to put some information from the client to the server and doDelete() method is used to delete some information from the server. When a call to servlet is made, its init() method is invoked and when the servlet is being destroyed, just before the garbage collection happens, it is destroyed() method is called. We will see init() method in detail some time later.

Advanced Programming Using Java

Distributed Programming with Java

6.4.4

Creating a Servlet

First of all let us create a servlet that simply prints Welcome to my page every time it is invoked. Listing 6.9 given below shows the code for Welcome servlet.
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Welcome extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ res.setContentType("text/html"); PrintWriter out=res.getWriter(); String host=req.getRemoteHost(); String addr=req.getRemoteAddr(); out.println("<HTML>"); out.println("<HEAD><TITLE>Welcome to my page</TITLE></HEAD>"); out.println("<BODY>"); out.println("<BIG>Welcome to my page </BIG>"); out.println("Your host name is: "+host+" and address is: "+addr); out.println("</BODY></HTML>"); } }
Listing 6.9 Welcome Servlet

The servlet overrides only the doGet() method. In this method, it first sets the ContentType of the HttpServletResponse object to text/html since the output that it has to send back is in HTML format. It then gets the PrintWriter object from the HttpServletResponse object so that it can send data via that stream. Then it writes the entire text that it has to send in HTML. It also uses getRemoteHost() and getRemoteAddr() methods to get the hostname and IP address of the machine that invoked this servlet. Note that both of these methods are applied to the HttpServletRequest object since the request for processing came via that object. To run this servlet, we will use a utility called servletrunner that comes free with JSDK. This utility is a substitute for the add-on servlet engine and can be used for testing servlets in case you dont have utilities like WebSphere installed on your server. Before accessing the servlet we must start the servletrunner utility. This utility tells the system in which directory the servlets are kept. Let us suppose that Welcome class file is present in c:\servlet_home directory, you will give the command to run servletrunner as: servletrunner d c:\servlet_home s c:\jsdk2.0\examples\servlet.properties The option d is used to specify the name of the directory in which servlet files are kept and s option is used to specify the name of the properties file. In the above example we are taking a sample property file that comes along with JSDK. The properties file can contain name value pair that can be loaded at runtime by a servlet. The name value pair denote a property and the value of that property. One can give one more option along

Advanced Programming Using Java

Distributed Programming with Java

with this, i.e., -p to specify the port number. If this option is omitted the default port is taken as 8080. Once your servletrunner is running, you can call your servlet by giving the following path in a browser:
http://localhost:8080/servlet/Welcome

Note that there is no directory called servlet, which exists physically existing. It is a logical directory that makes the system look for the directory where all servlets are kept and that information is provided by servletrunner. Fig. 6.12 given below shows the output of this servlet when called in a browser.

Fig. 6.12 Calling servlet Welcome

Let us now try to run this servlet when an html form data is asked for input from the user. Given below is an HTML code that asks for the user name and submits the result to the Welcome servlet (refer to program listing 6.10).
<html> <head> <title>Let's Introduce ourselves </title> </head> <body> <form method=get action="http://localhost:8080/servlet/Welcome1"> What's your name? <input type=text name="username"> <input type=submit> </form> </body> </html>
Listing 6.10 HTML file that will call Welcome1 servlet

The servlet is invoked in the FORM tag of html file where the method is specified as GET and action is specified as the URL that will invoke the servlet. Note that instead of Welcome servlet, we are calling Welcome1. Thats because the servlet will have to be changed now since it has to accept the parameter called username that the html file will

Advanced Programming Using Java

Distributed Programming with Java

send. This parameter will have the name that the user will enter. Program listing 6.11 given below shows the code for Welcome1 servlet.
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Welcome1 extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ res.setContentType("text/html"); PrintWriter out=res.getWriter(); String host=req.getRemoteHost(); String addr=req.getRemoteAddr(); String name=req.getParameter("username"); out.println("<HTML>"); out.println("<HEAD><TITLE>Welcome to my page </TITLE> </HEAD>"); out.println("<BODY>"); out.println("<BIG>"+name+", Welcome to my page </BIG>"); out.println("Your host name is: "+host+" and address is: "+addr); out.println("</BODY></HTML>"); } }
Listing 6.11 Welcome1 Servlet that accepts a parameter

This code is exactly the same as given in program listing 6.9 with the only difference being that getParameter(username) method is used to get the value of the parameter username, which is supplied to this servlet. You would notice that a servlet is in many ways similar to an applet. An applet can also get the parameter supplied by an html file in this way. Now place the Welcome1 servlet in the same directory in which you placed the Welcome servlet, run the servletrunner utility and open the html file given in program listing 6.10 in a browser. Fig. 6.13 shows the output when the html file is opened and fig. 6.14 shows the output when the submit button is clicked after typing in a name.

Advanced Programming Using Java

Distributed Programming with Java

Fig. 6.13 The output of html file in a browser

Fig. 6.14 The output when the Submit button is clicked

It is clear from fig. 6.14 that the moment Submit button was clicked, the query was sent to Welcome1 servlet. The Address area of the browser in fig. 6.14 confirms that. The servlet received Tom as the value in username parameter. Again this is evident from the Address area of the browser shown in fig. 6.14. The servlet accesses this username with the help of getParameter() method and prints the message as shown in fig. 6.14. In case you want that the HTML file should be able to use POST action as well as GET action, add the following code to your Welcome1 servlet.
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ doGet(req,res); }

This way any POST action will also make the servlet behave in the same way as a GET action call. Try to run your HTML file by giving the method as POST instead of GET and see if you get the same output or not. 6.4.5 Handling HEAD requests

One does not really have to handle HEAD requests by overriding the doHead() method of the servlet. Most of the time the default functionality of this method is sufficient. When a HEAD request is made to a servlet, it goes to the service() method, which then creates a modified HttpServletRequest object and then passes it to the doGet() method. The doGet() method proceeds as normal but only the headers it sets are returned to the client. The special response object suppresses all body output. Though this methodology is quite simple and effective, it can be made more effective if doGet() method is able to detect the HEAD requests and return early instead of executing the code that will in any way be suppressed by the response object. It can be done by adding the following line in the doGet() at the beginning:

Advanced Programming Using Java

Distributed Programming with Java

if (req.getMethod().equals(HEAD)) return;

6.4.6

init() Method

The init() method of a servlet works in the very much same way as an applets init() method. It is used to perform initialisation like assigning values, creating or loading objects, etc. This function is called before servlet handles its first request. This method accepts an object of ServletConfig class. This class can be used to get the initialisation parameters. These parameters are supplied to the servlet in different ways by different environments. For example, in Java Web Server, initialisation parameters are set during the registration process. In servletrunner utility, initialisation parameter can be supplied by modifying the properties file. Remember the name of the properties file must be specified with s option. To understand the working of init() method in a better way let us consider a servlet that prints a number every time a user accesses it. This number will be initialised to 10 in the properties file and this initialisation parameter will be accessed in the servlets init() method. Then the doGet() method of the servlet will increment the count by 2 and prints it. Program listing 6.12 given below shows the code for Count servlet.
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Count extends HttpServlet{ int c; public void init(ServletConfig config) throws ServletException{ super.init(config); String initial=config.getInitParameter("initial"); try{ c=Integer.parseInt(initial); } catch(NumberFormatException e){c=0;} } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ res.setContentType("text/html"); PrintWriter out=res.getWriter(); c=c+2; out.println("Next Number is : "+c); } }
Listing 6.12 The code for Count servlet

The program listing 6.12 declares an int variable c that will hold the count. Note that the init() method of servlet must always call the init() method of superclass with the ServletConfig object that it has received. Let us understand why this is necessary. The ServletConfig object is available to the init() method. But what happens if any

Advanced Programming Using Java

Distributed Programming with Java

other method of the servlet needs it. Therefore, the init() method invokes the init() method of superclass HttpServlet which is extended from GenericServlet. The GenericServlet class implements ServletConfig class itself. Thus the config object can be reused by a servlet by invoking method to itself. This means that instead of saying
String initial=config.getInitParameter(initial);

one can say,


String initial=getInitParameter(initial);

Thus,

of initialisation parameter initial is accessed by getInitParameter() method. Since any parameter that is accepted is String type, it is converted to integer type using parseInt() method. In case this value is not integer type, c is initialised to 0. The doGet() method simply increments the value of c by 2 and writes it to the response object. Now to be able to send initialisation parameters to a servlet, either create a new properties file or modify the sample servlet.properties file in JSDK2.0\examples folder. The entry in that file should be made as:
servlet.count2plus.code=Count servlet.count2plus.initArgs=\ initial=10

the

value

The first line specifies the name for the Count.class servlet as count2plus. This means in a browser you can specify the name of the servlet Count as count2plus. The second line specifies the initialisation argument initial with a value 10. A back slash (\) is given in case there are more than one arguments. So in this case using a back slash is not a must. After adding these two lines in the servlet.properties file in JSDK2.0\examples directory, call the servletrunner utility by giving the following command: servletrunner d c:\servlet_home s c:\jsdk2.0\examples\servlet.properties And then open a browser window and run the servlet by giving the path as
http://localhost:8080/servlet/count2plus

Fig. 6.15 shows the output of this servlet in a browser. The value being shown is 12 since the initial parameter contained a value 10.

Fig. 6.15 First call to the count2plus servlet

Advanced Programming Using Java

Distributed Programming with Java

Now open another browser window and run this servlet again, you will now see the value 14 displayed in the browser window (refer to fig. 6.16).

Fig. 6.16 Second call to the count2plus servlet

Advanced Programming Using Java

Distributed Programming with Java

6.4.7

Some important Servlet Methods

Given below is the list of some important Servlet methods with their description. All of these methods belong HttpServletRequest class.
Method getServerName() getProtocol() getServerPort() getMethod() getPathInfo() getPathTranslated() Description Returns the host name of the server that received the request Returns the protocol and version Returns the port at which the request was received Returns the method that invoked the servlet (POST, GET, etc.) Gets any optional extra path information following the servlet path of this request's URI, but immediately preceding its query string. Gets any optional extra path information following the servlet path of this request's URI, but immediately preceding its query string, and translates it to a real path. Gets the part of this request's URI that refers to the servlet being invoked. Applies alias rules to the specified virtual path and returns the corresponding real path, or null if the translation can not be performed for any reason. Gets any query string that is part of the HTTP request URL. Gets the hostname of the user making this request Gets the IP address of the user making this request Gets the name of the user making this request Returns the Internet Media Type of the request entity data, or null if not known. Returns the size of the request entity data, or -1 if not known.

getServletPath() getRealPath()

getQueryString() getRemoteHost() getRemoteAddr() getRemoteUser() getContentType() getContentLength()

The following methods can be invoked on ServletConfig object. Method getInitParameterNames() getInitParameter(name) Description Returns an Enumeration containing names of all initialisation parameters Returns the value in the initialisation parameter name

There is one more method that returns the information about the servlet like its author, version, etc. This function is called getServletContext() and is written in the same way as the getAppletContext() method. 6.4.8 Communication between Applets and Servlets

Let us now see how a client applet calls a servlet. A client applet creates a URL for the servlet with which it has to communicate and then opens a connection with that URL. Then an output stream is obtained from the connection object and the request data is sent to the servlet via the output stream. Before sending data to the servlet, the content type of request object set to application/x-www-form-urlencoded. This is a standard content type recognized by all web servers and causes the servlet to treat this request as a POST request.

Advanced Programming Using Java

Distributed Programming with Java

The servlet, on the other hand receives this data via HttpServletRequest object, processes the request and sends the result back via HttpServletResponse object. Let us take an example to understand things in a better way. Refer to section 6.3.3 where we took the example of an Employee database and used RMI to create remote object and invoked its methods. We will take the same example and use servlet in the middle layer. Therefore the remote object contacts a servlet and servlet in turn invokes the methods of remote object. For this purpose we will create a proxy object. The client will create an instance of proxy object and pass the servlet base to it. The servlet base is the logical path where the servlet exists. Then the client invokes the methods of this proxy object. The proxy objects class file defines each method that can be invoked remotely. Program listing 6.13 given below shows the code for UserDatabaseProxy class. The definition of StartDatabase, UserData, UserDatabase, and UserDatabaseImpl class remain the same.
import java.io.*; import java.net.*; import java.util.*; public class UserDatabaseProxy { URL servlet; // The URL to the called servlet. ObjectInputStream in; // Input stream from the servlet. Integer code; // Code for the operation to be performed public UserDatabaseProxy(URL web) { try{ servlet = new URL(web,"servlet/DatabaseServlet"); } catch (MalformedURLException e){} } // Adds a user to the database public String createUser(UserData data) throws Exception { code=new Integer(2); Serializable objs[] = {code,data }; in = postObjects(servlet, objs); String id = (String)in.readObject(); in.close(); return id; }

// Modifies a user in the database public void editUser(String userid, UserData data) throws Exception { code=new Integer(3); Serializable objs[] = { code, userid, data };

Advanced Programming Using Java

Distributed Programming with Java

in = postObjects(servlet, objs); in.close(); } // Deletes a user from the datbase public void deleteUser(String userid) throws Exception { code=new Integer(4); Serializable objs[] = { code, userid }; in = postObjects(servlet, objs); in.close(); } // Gets a user from the datbase public UserData getUser(String userid) throws Exception { code=new Integer(1); Serializable objs[] = { code, userid }; in = postObjects(servlet, objs); UserData data = (UserData)in.readObject(); in.close(); return data; } // Lists a user from the datbase public Hashtable listUsers() throws Exception { code=new Integer(0); Serializable objs[] = { code }; in = postObjects(servlet, objs); Hashtable database = (Hashtable)in.readObject(); in.close(); return database; } static public ObjectInputStream postObjects(URL servlet, Serializable objs[]) throws Exception { URLConnection con = servlet.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setRequestProperty("Content-Type", "application/xwww-form-urlencoded"); // Write the arguments as post data ObjectOutputStream out = new ObjectOutputStream( con.getOutputStream()); int numObjects = objs.length; for (int x = 0; x < numObjects; x++) { out.writeObject(objs[x]); } out.flush(); out.close();

Advanced Programming Using Java

Distributed Programming with Java

return new ObjectInputStream( con.getInputStream() ); } }


Listing 6.13 Code for proxy object (UserDatabaseProxy.java)

This UserDatabaseProxy class accepts the servlet base in its constructor method, which will denote the web-base address of the servlet. The name of the servlet that we will write to call the remote object is DatabaseServlet. Thus a new URL is created with /servlet/DatabaseServlet added to the servlet base. This URL will form the actual full path for the servlet. Note that there are methods for listing users, getting a user detail, deleting a user, modifying user details and creating a new user in this class. These are again proxy methods that are called by the client and they in turn call on the servlet that will handle the request. Since there is only one servlet for handling all these request, an Integer code is sent along with the required data to the servlet. The codes for each operation is given below: LIST 0 GET 1 CREATE 2 EDIT 3 DELETE 4 In each of these methods, an array of Serializable objects and the servlet URL is sent to a method called postObjects(). The contents of the Serializable array differ in each method. In case of creating a user a code, and a UserData object is sent whereas in case of editing a user details a code, a UserData object and the user id is sent. In case of deleting and getting user details the code and the user id are sent, and finally in case of listing users, only the code is sent. The postObjects() method opens the connection to the URL and allows the connection to accept input and give output with the help of setDoInput() and setDoOutput() methods. It also sets the servlets request objects content type property as application/x-www-form-urlencode with the help of the following command:
con.setRequestProperty("Content-Type", urlencoded"); "application/x-www-form-

Setting a content type like this ensures that the servlets doPost() method will be called. Then it gets the output stream from the URLConnection object, this is the output stream for the servlet. The postObjects() method then writes each serialized object that it had accepted via this output stream to the servlet. The servlet receives these objects via its request object, processes it and sends the result back. These results can be received by getting the input stream of the servlet. Each method can access this Input Stream object and send the result back to the client. Now let us see what happens inside the servlet. Given below is the code for DatabaseServlet (refer to program listing 6.14)

Advanced Programming Using Java

Distributed Programming with Java

import import import import import

java.io.*; java.rmi.*; java.util.*; javax.servlet.*; javax.servlet.http.*;

public class DatabaseServlet extends HttpServlet { String registry; // The path to the RMI registry UserDatabase db; // The database access object public void init(ServletConfig config) throws ServletException { super.init(config); registry = config.getInitParameter("registry"); if (registry == null) registry = "//localhost"; try { String name = registry + "/DB1"; db = (UserDatabase)Naming.lookup(name); } catch (Exception e) { e.printStackTrace(); } } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Open the I/O streams ObjectInputStream in = new ObjectInputStream(req. getInputStream() ); ObjectOutputStream out = new ObjectOutputStream( resp. getOutputStream() ); try { // Find out which operation Integer codeInt=(Integer)in.readObject(); int code=codeInt.intValue(); System.out.println(code); if (code==0){ Hashtable database = db.listUsers(); out.writeObject(database); } else if (code==1){ String id=(String)in.readObject(); UserData data=db.getUser(id); out.writeObject(data); } else if (code==2){ UserData data=(UserData)in.readObject(); String id=db.createUser(data); out.writeObject(id);

Advanced Programming Using Java

Distributed Programming with Java

} else if (code==3){ String id=(String)in.readObject(); UserData data=(UserData)in.readObject(); db.editUser(id,data); } else if (code==4){ String id=(String)in.readObject(); db.deleteUser(id); } } catch (Exception e) { e.printStackTrace(); } // Close the I/O streams in.close(); out.close(); } }
Listing 6.14 Code for the Servlet that in turn invokes the remote methods (DatabaseServlet.java)

The DatabaseServlet has two variables a String object called registry that will hold the path of the registry running at the server, and a UserDatabase object called db. This object will be used to invoke the methods of remote object. The init() method of the servlet tries to find out if the properties file has specified any path where the registry is running. If no entry exists in the properties file, it assumes that the registry is running at the localhost and it tries to get reference to the remote object called DB1 from the rmiregistry. Then the doPost() method of the servlet opens an input and output stream from the request and response object respectively. All the methods that invoke the servlet will definitely send an Integer value representing the code of the operation to be performed. Thus, the servlet uses readObject() method to retrieve the code from the input stream. According to the code that is sent to the servlet, different actions are performed. If the code is 0, a call to listUsers() method of the remote object is made which returns a Hashtable object. This object is written to the output stream retrieved from the response object. If the code is 1, a call to the getUser() method is made. But this method requires the id of the user, which is sent to the servlet (refer to UserDatabaseProxy classs getUser() method, along with code id was also sent). Thus, readObject() method is used to retrieve the user id from the input stream and the id that is received is supplied to the getUser() method of the remote object. This method returns a UserData object, which is again written to the output stream received from the response object of the servlet. The explanation for the rest of the methods is left to the readers. Now just make a small change to the DatabaseApplet class. Instead of the following lines of code in the original program:
String host = this.getCodeBase().getHost(); String name = "//" + host + "/DB1";

Advanced Programming Using Java

Distributed Programming with Java

db = (UserDatabase)java.rmi.Naming.lookup(name);

write these two statements:


URL servletBase = new URL("http://localhost:8080"); db = new UserDatabaseProxy(servletBase);

Compile all programs and run the servletrunner utility in a separate dos prompt window, the StartDatabase class in separate command window and the appletviewer in the third command window.

6.4 Case Study College Student Enrollment System (Contd.)


Refer to the college student enrollment system case study that we have been referring to in previous chapters. We will now make a few modifications to the case study so that it uses RMI and servlets to interact with the server. For doing this we will create a database proxy object that in turn will call the servlet, which in turn will call the remote database objects methods. We will first see the definition of the proxy object. Refer to program listing 6.15 to see the definition of UserDatabase class. This is the remote interface for the remote object.
package college.student; public interface UserDatabase extends java.rmi.Remote { public String processApplication(Application appl) throws java.rmi.RemoteException; }
Listing 6.15 The Remote Interface (UserDatabase.java)

Note that the interface has only one method since the remote object just has to process the data that is coming in. The processApplication() method accepts an Application object and returns a String that will indicate if the student has been admitted or not. Now let us see the definition of the remote class that implements the remote interface given in program listing 6.15. Refer to program listing 6.16 to see the definition of the remote objects class. The class is called UserDatabaseImpl.java.
package college.student; import java.rmi.*; import java.rmi.server.*; public class UserDatabaseImpl extends java.rmi.server.UnicastRemoteObject implements UserDatabase { static Course cs[]= new Course[3]; public UserDatabaseImpl() throws java.rmi.RemoteException

Advanced Programming Using Java

Distributed Programming with Java

{ String strCoresub[] = {"c","c++","ooads", "Networking", "Oracle","vc","unix","vb"}; String strOptsub[] = {"NT","JAVA","SQL"}; cs[0]=createCourse("MDMC",strCoresub,strOptsub); cs[0].setEntranceQual(new Long(75)); cs[0].setMaxStudents(5); String strCore2[] = {"unix","c","ooads"}; String strOpt2[] = {"DBA","C++"}; cs[1]=createCourse("UCO",strCore2,strOpt2); cs[1].setEntranceQual(new Long(75)); cs[1].setMaxStudents(5); String strCore3[] = {"c++"}; String strOpt3[] = {"OOADS","JAVA"}; cs[2]=createCourse("C++" ,strCore3, strOpt3); cs[2].setEntranceQual(new Long(75)); cs[2].setMaxStudents(5); } public static Course createCourse(String strName, String strCore[],String strOpt[]){ CoreSubject core[] = new CoreSubject[strCore.length]; for(int i =0;i<strCore.length; i++){ core[i] = new CoreSubject(strCore[i]); } OptSubject opt[] = new OptSubject[strOpt.length]; for(int i =0;i<strOpt.length; i++) opt[i] = new OptSubject(strOpt[i]); return(new Course(strName ,core, opt)); } public String processApplication(Application appl1){ int ctr =-1; String csName=appl1.getCSDet(); //find the course by matching returned name with existing courses for(ctr=0;ctr<3;ctr++) { if(cs[ctr].getName().equals(csName)) break; } String message1=null; if (appl1.appApl(cs[ctr])) { message1 = "Congrats! The student is selected"; //logically should create a student with id etc cs[ctr].setCurrSt(); } else

Advanced Programming Using Java

Distributed Programming with Java

{ message1 = "Sorry! Student is not enrolled"; } return message1; } }


Listing 6.16 Implementation of the Remote Interface (UserDatabaseImpl.java)

You are already familiar with the logic of the program. The UserDatabaseImpl class implements the processApplication() method and returns Congrats! The student is selected if the student has more than 75% marks and there is a seat available in the batch, otherwise it returns a message Sorry! The student is not enrolled. Next we will see the implementation of the proxy object that the client will use to communicate with the server. This class is called UserDatabaseProxy. Program listing 6.17 given below shows the definition of this file.
package college.student; import java.io.*; import java.net.*; import java.util.*; public class UserDatabaseProxy { URL servlet; //The fully-qualified URL to the called servlet. URL webBase; // The complete URL to the servlet web server (ex. 'http://www.sun.com:8080'). ObjectInputStream in; // Input stream from the servlet. public UserDatabaseProxy(URL web) { webBase = web; } public String processApplication(Application appl1) throws Exception { servlet = new URL(webBase, "servlet/DatabaseServlet"); Serializable objs[] = { appl1 }; in = ServletWriter.postObjects(servlet, objs); String id = (String)in.readObject(); in.close(); return id; } }
Listing 6.17 The proxy object (UserDatabaseProxy.Java)

The UserDatabaseProxy class declares two variables webBase that will store the logical path where the servlet is located and servlet that will store the full path to the servlet. The

Advanced Programming Using Java

Distributed Programming with Java

constructor method of this class accepts a logical path to the servlet and initialises webBase with that value. The processApplication() method of this class accepts an Application object, initialises servlet with the full path to the servlet, creates an array of Serializable elements, and stores Application object in it. It then calls the postObjects() method of ServletWriter class and passes the path of the servlet and the arguments that the servlet would need in the form of Serializable array to it. The ServletWriter class accepts the path to the servlet and the arguments to be sent to it, creates a URL to that servlet and opens a connection to that servlet. It then passes the elements in the Serializable array to the servlet through its output stream and accepts the output from the servlet through its input stream. The code for ServletWriter class is given in program listing 6.18.
package college.student; import java.net.*; import java.io.*; public class ServletWriter { static public ObjectInputStream postObjects(URL servlet, Serializable objs[]) throws Exception { URLConnection con = servlet.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setRequestProperty("Content-Type", "application/xwww-form-urlencoded"); // Write the arguments as post data ObjectOutputStream out = new ObjectOutputStream (con.getOutputStream()); int numObjects = objs.length; for (int x = 0; x < numObjects; x++) { out.writeObject(objs[x]); } out.flush(); out.close(); System.out.println("ServletWriter"); return new ObjectInputStream( con.getInputStream() ); } }
Listing 6.18 The ServletWriter class

Now we will see the code for DatabaseServlet class. This class will not be a part of the package and hence it must exist in a directory above the college/student directory. If your college/student directory exist at the root directory, create this file in the root directory. Program listing 6.19 shows the code for DatabaseServlet class.
import import import import java.io.*; java.rmi.*; java.util.*; javax.servlet.*;

Advanced Programming Using Java

Distributed Programming with Java

import javax.servlet.http.*; import college.student.*; public class DatabaseServlet extends HttpServlet { String registry; // The path to the RMI registry UserDatabase db; // The database access object public void init(ServletConfig config) throws ServletException { super.init(config); System.out.println("beg init of servlet"); // Get the location of the RMI registry. registry = config.getInitParameter("registry"); // If undefined, assume the local host if (registry == null) registry = "//localhost"; try { // Now get the database object String name = registry + "/DB1"; db = (UserDatabase)Naming.lookup(name); } catch (Exception e) { e.printStackTrace(); } } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ObjectInputStream in = new ObjectInputStream (req.getInputStream() ); ObjectOutputStream out = new ObjectOutputStream (resp.getOutputStream() ); try { Application appl1 = (Application) in.readObject(); System.out.println("got Appl object"); String message1 = db.processApplication(appl1); System.out.println("Processed"); out.writeObject(message1); } catch (Exception e) { e.printStackTrace(); } // Close the I/O streams in.close(); out.close(); } }
Listing 6.19 The DatabaseServlet class

Advanced Programming Using Java

Distributed Programming with Java

The DatabaseServlet receives the arguments via its request objects input stream and calls the processApplication() method of the remote object. It then writes the result that it received from the remote object to the response objects output stream. Now the last thing that is needed is to start the remote registry and bind the remote object with it. Program listing 6.20 given below shows the code for such a program, it is called
StartDatabase.java package college.student; import java.rmi.*; import java.rmi.registry.*; import java.io.*; import java.util.*; import java.net.*; public class StartDatabase { public StartDatabase() { try { // Start up the registry Registry reg = java.rmi.registry.LocateRegistry. createRegistry(1099); // Create the Database object UserDatabaseImpl db = new UserDatabaseImpl(); // Bind it to the registry Naming.rebind("DB1", db); } catch (java.rmi.UnknownHostException unx) { unx.printStackTrace(); } catch (java.rmi.RemoteException rex) { rex.printStackTrace(); } catch (java.net.MalformedURLException mfx) { mfx.printStackTrace(); } } static public void main(String args[]) { System.setSecurityManager(new RMISecurityManager()); StartDatabase starter = new StartDatabase(); } }
Listing 6.20 The StartDatabase class

Advanced Programming Using Java

Distributed Programming with Java

SUMMARY
Client/Server systems have three components the user interface layer, the information processing layer and the information storage layer. The information processing layer may reside on either the client or the server machine. On Internet, the client interacts with the server with the help of TCP/IP protocol. DCE is an industry-standard, vendor-neutral set of distributed computing technologies by Open Software Foundation, in which distributed systems are organized as cells. DCOM is an extension of COM, which makes it possible for a COM object on one machine to interact with another COM object on a remote machine. DCOM provides very good security features and is object oriented (in contrast to DCE that is procedure oriented) but it does not give good performance on nonWindows platform. CORBA provides an excellent framework for designing distributed applications. In CORBA objects are accessed via ORBs (Object Request Brokers), and the interface to ORB are written in IDL (Interface Definition Language). CORBA is object-oriented, is an international standard recognized by majority of software vendors, and both server and client can be distributed in CORBA. RMI is Javas answer to designing distributed applications that supports seamless remote invocation on objects in different virtual machines. RMIs architecture is somewhat similar to that of CORBA. In RMI, a local object interacts with the remote object with the help of a remote interface. The use of remote interface allows server to differentiate between their local and remote interfaces, eliminates the need of having the server class file present at the client side, and presents different access modes to the remote object. In RMI, the local object invokes the methods of stub class, which in turn passes these method calls to the remote reference layer. The remote reference layer on the client machine interacts with the remote reference layer on the server machine, which in turn invokes the methods of the server skeleton. The skeleton invokes the corresponding methods of the remote object and passes the result back in the same fashion. RMI applets have a few disadvantages too, IE and Netscape Navigator do not support RMI fully, which makes is impossible for IE and Netscape users t use RMI applets.

Advanced Programming Using Java

Distributed Programming with Java

The steps to designing a distributed application using RMI are: Define the remote interface Create the remote object that will implement the remote interface Generate the stub and skeleton classes for the remote object Create the client object Start the registry and run the server and client programs The remote object must register itself with the remote registry. CGI was the first application to be used to extend the web servers. But it needs to start a separate process for each CGI call. FastCGI is supposed to cover up the drawbacks of CGI and it does that by starting only one process for a particular CGI script. But in case of concurrent calls for the same CGI script, separate processes are created. Server extensions differ from CGI and FastCGI in terms of how they run. CGI and FastCGI run as external applications and therefore are not able to make use of servers capabilities. Server extensions run inside the server and can take the advantage of servers capabilities but a crashed server extension can bring the entire network down. ASP and server-side Java Script are good choices to create dynamic content. Servlets are server-side Java programs that can be loaded dynamically. A servlet runs inside a JVM on the server and thus is safe and portable. A Servlet handles each request by starting a separate thread, and as a result, they become more efficient and scalable. servletrunner utility can be used to run the servlets. A Servlet class can either be extended from HttpServlet class or GenericServlet class. HttpServlet class is used to create servlets that use HTTP protocol. The doGet() and doPost() methods are to be overridden in case of HTTP servlets and service() method needs to be overridden in case of generic servlets. The service() method of HttpServlet class automatically send the requests to either doGet(), doPost(), or doHead(), etc. methods depending on the type of the call. The doHead() method need not be overridden in most of the cases. The init() method of the servlet accepts a ServletConfig object that can be used to get the initialisation parameters of the servlet.

Advanced Programming Using Java

Distributed Programming with Java

The initialisation parameters can be passed to the servlet via the properties file and can be received by the servlet with the help of getInitParameter() method. An applet can communicate with the servlet by: Creating a URL to the servlet Opening the connection to the URL Sending the required data to the servlet with the help of the output stream of the URL object Retrieve the result from the servlet with the help of the input stream of the URL

Das könnte Ihnen auch gefallen