Jee Servlets

Embed Size (px)

Citation preview

  • 8/13/2019 Jee Servlets

    1/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 usingJavas distributed Object model. You will be able to design distributed applications using

    RMI and Servlets.

    SCOPE

    6.1Distributed Application Design6.1.1 Distributed Programming on Internet and Intranets6.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.2Java Distributed Object Model6.2.1 Advantages6.2.2 Disadvantages

    6.3Servlets6.3.1 History6.3.2 Introduction to Java Servlets6.3.3 Java Servlet API6.3.4 Creating a Servlet6.3.5 Handling HEAD requests6.3.6 init() method6.3.7 Some important Servlet Methods6.3.8 Communication between Applets and Servlets

  • 8/13/2019 Jee Servlets

    2/34

    Advanced Programming Using Java Distributed Programming with Java

    6.1Distributed Application DesignMost of the development and deployment environments today are networked. Therefore

    it becomes necessary for the applications that are designed to be distributed. Distributedapplications 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, theinformation 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 thevalues 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 tothe 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.

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

    machine

    Client Machine Server Machine

    User

    Interface

    Layer

    (Browser)

    Information

    Processing

    Layer

    (Application

    Client)

    Information

    Storage Layer

    (Application

    Server)

  • 8/13/2019 Jee Servlets

    3/34

    Advanced Programming Using Java Distributed Programming with Java

    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 IntranetsInternet 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 aclient program is executed on multiple host computers. The client interacts with theserver 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 toprocess 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) isan 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 isdesigned 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 ofDCE 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.

    Client Machine Server Machine

    User

    Interface

    Layer(Browser)

    Information

    Processing

    Layer

    (ApplicationClient)

    Information

    Storage Layer

    (ApplicationServer)

  • 8/13/2019 Jee Servlets

    4/34

    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 acrossthe 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 distributedapplications. The services and technologies used within a DCE cell consist of the

    following: Directory ServiceStores 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 ServiceThis 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 ofTCP/IP transport layer and transparently performs connection management. Itreplaces TCP sockets as the basic mechanism for client/server communication.

    DCE ThreadsDCE 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 fordeveloping distributed applications. DCOM has a long history attached to it. DCOM is

    essentially distributed COM. Therefore, to understand DCOM let us first see what isCOM.

    It all started with OLE (Object Linking and Embedding) technology that was used tosupport 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. Notethat 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 objectscould 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 firstinvokes 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.

  • 8/13/2019 Jee Servlets

    5/34

    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 methodsof 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 localobject invokes the methods of local COM library of the remote object it is trying toaccess. 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. Itssecurity 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 transferredfrom 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 architecturefor 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 toORB is written in IDL (Interface Definition Language), and is known as IDL stub. IDL

    provides a programming language-independent mechanism for describing the methods ofan 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 thecorresponding 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 thencommunicates the results back to the client object. This remote method invocation is

    depicted pictorially in fig. 6.3.

  • 8/13/2019 Jee Servlets

    6/34

    Advanced Programming Using Java Distributed Programming with Java

    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 andweb servers were servers, both clients and servers can be distributed in CORBA.

    CORBA implementation is language-independent. You just have to provide IDLinterface 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 distributedapplications, 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 otherdrawback in it and thus, there was a need of a mechanism that provides the capability todevelop 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 procedure-

    oriented. 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 notgive good performance on platforms other than Windows. Also, DCOM does notsupport 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 Javaapplications.

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

    Client Host Server Host

    Client

    Object

    Server

    Object

    IDL Stub IDL Skeleton

    ORB

  • 8/13/2019 Jee Servlets

    7/34

    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 distributedobjects 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.2Java Distributed Object ModelJavas 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

    objector 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 thatis 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 remoteinterfaces (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. LikeCORBA 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 sameway 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. Theremote 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 ofcommunication 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

  • 8/13/2019 Jee Servlets

    8/34

    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 thetwo 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 three-

    tiered architecture of Java RMI pictorially.

    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 r mi r egi st r y 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 theremote 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 iscopied 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 AdvantagesJava RMI is a great option for Internet programming. There are many advantages ofusing 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 toworry about creating your own communication classes and packaging them with the

    applet.

    Client

    Object

    Server

    Object

    Stub Skeleton

    Remote Reference Layer Remote Reference Layer

    Transport Layer Transport Layer

    Lower Layer

    Protocols

    Lower Layer

    Protocols

  • 8/13/2019 Jee Servlets

    9/34

    Advanced Programming Using Java Distributed Programming with Java

    An executable version of RMI registry is available in Java 1.1 and 1.2 runtimepackages. Thus, you are able to deploy your server applications without needing anexpensive application server.

    RMI can also tunnel its transaction through HTTP, if necessary. This allows the userswho 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 executeserver-side operations with simple function calls.

    6.2.2 DisadvantagesDespite having many advantages, Java RMI is still not so popular for developing

    distributed applications. This is because RMI applets have many limitations. Theselimitations are given below:

    The most popular browsers like Internet Explorer and Netscape Navigator do notsupport RMI fully. Navigator does support RMI on most of the platforms but does notsupport 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 connectedto Internet via a proxy server to access RMI applets.

    6.3ServletTill now we have seen how Java can be used to create client side applications and alsoapplets 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 Javaapplications that can be loaded dynamically. But before talking about Servlets, let us look

    at the history of server-side applications.

    6.4.1 HistoryA 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, someapplications 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

  • 8/13/2019 Jee Servlets

    10/34

    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 takeadvantage 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 theresponse 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.

    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 mostof the web servers are not using FastCGI technique. Fig. 6.10 shows the working of a

    FastCGI based server.

    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 FastCGI A

    Call for FastCGI B

    Call for FastCGI A

    Process for FastCGI A

    Process for FastCGI B

    Server

    Call for CGI A

    Call for CGI B

    Call for CGI A

    Process for CGI A

    Process for CGI B

    Process for CGI A

    Server

    Call for Server Extension A

    Call for Server Extension B

    Call for Server Extension A

    Server Extension A

    Server Extension B

  • 8/13/2019 Jee Servlets

    11/34

    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 APIknown 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 reliabilityhazards. 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 theworking 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 JavaScript 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 ServletsJava 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 Javasmultithreading capability. It creates a separate thread to handle each request (refer to fig.

    6.12).

    Fig. 6.12 Servlet based web server

    As a result servlets become more efficient and scalable. Another advantage of servlets isthat 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

    Server

    Call for Servlet A

    Call for Servlet B

    Call for Servlet A

    JVM

    Servlet A

    Servlet B

  • 8/13/2019 Jee Servlets

    12/34

    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 APIThe 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 j avax. ser vl et and j avax. ser vl et . ht t p. The j avax. ser vl et package is used

    to create proptocol-independent servlets. Thej avax. ser vl et . ht t ppackage is used to

    create HTTP servlets. All servlets must implement Ser vl et interface. A protocol

    independent servlet can extend the classj avax. ser vl et . Gener i cSer vl et (this class

    implements Ser vl et interface) and an HTTP servlet can extend

    j avax. ser vl et . ht t p. Ht t pSer vl et class. Ht t pSer vl et class is a subclass of

    Gener i cSer vl et 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 ser vi ce( ) method. The ser vi ce( ) method accepts two parameters a Servl etRequest and a

    Servl etResponse type objects. The Servl etRequest object specifies the clients

    request and the Servl etResponse object specifies the response of the servlet to that

    request.

    An Ht t pSer vl et , on the other hand, does not usually overrides the ser vi ce( )

    method. This is because it has specific methods called doGet ( ) and doPost ( ) to

    handle specific requests. The ser vi ce( ) method in turn dispatches requests to these

    methods. Both doPost ( ) and doGet ( ) methods accepts two arguments an

    Ht t pServl et Request object and an Ht t pServl etResponse 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 ser vi ce( ) method, by default, also calls

    the doOpt i ons( ) method when it receives an OPTIONS request, and doTr ace( ) when

    it receives a TRACE request. The default implementation of doOpt i ons( )

    automatically determines what HTTP options are supported and returns that information.

    The default implementation of doTr ace( ) 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 doDel ete( )

    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 dest r oyed( ) method is

    called. We will see init() method in detail some time later.

  • 8/13/2019 Jee Servlets

    13/34

    Advanced Programming Using Java Distributed Programming with Java

    6.4.4 Creating a ServletFirst 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.

    i mpor t j ava. i o. *;i mpor t j avax. ser vl et . *;

    i mpor t j avax. ser vl et . ht t p. *;

    publ i c cl ass Wel come ext ends Ht t pServl et{publ i c voi d doGet ( Ht t pSer vl etRequest r eq, Ht t pSer vl etResponse

    r es) t hr ows Ser vl et Except i on, I OExcept i on{r es. set Cont ent Type( "t ext / ht ml ") ;Pr i nt Wr i t er out =r es. get Wr i t er ( ) ;St r i ng host =r eq. getRemot eHost ( ) ;St r i ng addr =r eq. get RemoteAddr ( ) ;out . pr i nt l n( "") ;out . pr i nt l n( "Wel come t o my

    page" ) ;out . pr i nt l n( "") ;out . pr i nt l n( "Wel come t o my page ") ;out . pr i nt l n( "Your host name i s: "+host +" and addr ess i s:

    "+addr ) ;out . pr i nt l n( "") ;

    }}

    Listing 6.9 Welcome Servlet

    The servlet overrides only the doGet ( ) method. In this method, it first sets the

    ContentType of the Ht t pSer vl etResponseobject to text/html since the output that

    it has to send back is in HTML format. It then gets the Pr i nt Wr i t er object from the

    Ht t pServl et Responseobject so that it can send data via that stream. Then it writesthe entire text that it has to send in HTML. It also uses get Remot eHost ( ) and

    getRemot eAddr ( ) 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

    Ht t pServl et Request object since the request for processing came via that object.

    To run this servlet, we will use a utility called servletrunnerthat comes free with JSDK.

    This utility is a substitute for the add-on servlet engine and can be used for testingservlets in case you dont have utilities like WebSphere installed on your server. Before

    accessing the servlet we must start the servletrunnerutility. 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 pairdenote a property and the value of that property. One can give one more option along

  • 8/13/2019 Jee Servlets

    14/34

    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 thefollowing path in a browser:

    ht t p: / / l ocal host : 8080/ ser vl et / Wel come

    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 keptand 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).

    Let ' s I nt r oduce our sel vesWhat ' s your name?

    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 bechanged now since it has to accept the parameter called usernamethat the html file will

  • 8/13/2019 Jee Servlets

    15/34

    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.

    i mpor t j ava. i o. *;i mpor t j avax. ser vl et . *;i mpor t j avax. ser vl et . ht t p. *;publ i c cl ass Wel come1 ext ends Ht t pServl et {

    publ i c voi d doGet ( Ht t pSer vl etRequest r eq, Ht t pSer vl etResponser es) t hr ows Ser vl et Except i on, I OExcept i on{

    r es. set Cont ent Type( "t ext / ht ml ") ;Pr i nt Wr i t er out =r es. get Wr i t er ( ) ;St r i ng host =r eq. getRemot eHost ( ) ;St r i ng addr =r eq. get RemoteAddr ( ) ;St r i ng name=r eq. get Par ameter( "user name") ;out . pr i nt l n( "") ;out . pr i nt l n( "Wel come t o my page

    " ) ;out . pr i nt l n( "") ;out . pr i nt l n( ""+name+" , Wel come t o my page " ) ;

    out . pr i nt l n( "Your host name i s: "+host +" and addr ess i s:"+addr ) ;

    out . pr i nt l n( "") ;}

    }

    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 get Paramet er ( username) method is used to get the value of the parameter

    user name, 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 theWelcome 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.

  • 8/13/2019 Jee Servlets

    16/34

    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 sentto Welcome1 servlet. The Address area of the browser in fig. 6.14 confirms that. The

    servlet received Tomas the value in usernameparameter. Again this is evident from theAddress area of the browser shown in fig. 6.14. The servlet accesses this username with

    the help of getPar ameter( ) 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.

    publ i c voi d doPost ( Ht t pSer vl et Request r eq, Ht t pSer vl et Responser es) t hr ows Ser vl et Except i on, I OExcept i on{

    doGet ( r eq, r es) ;

    }

    This way any POST action will also make the servlet behave in the same way as a GETaction 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 requestsOne 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 ser vi ce( ) method, which

    then creates a modified Ht t pServl etRequest object and then passes it to thedoGet ( ) 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:

  • 8/13/2019 Jee Servlets

    17/34

    Advanced Programming Using Java Distributed Programming with Java

    i f ( r eq. get Met hod( ) . equal s( HEAD) ) r et ur n;

    6.4.6 init() MethodThe init() method of a servlet works in the very much same way as an applets i ni t ( )

    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 methodaccepts an object of Ser vl et Conf i g 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 besupplied by modifying the properties file. Remember the name of the properties file must

    be specified with s option.

    To understand the working of i ni t ( ) 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

    i ni t ( ) 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.

    i mpor t j ava. i o. *;i mpor t j avax. ser vl et . *;i mpor t j avax. ser vl et . ht t p. *;

    publ i c cl ass Count ext ends Ht t pSer vl et {i nt c;

    publ i c voi d i ni t ( Ser vl et Conf i g conf i g) t hr owsSer vl et Except i on{

    super . i ni t ( conf i g) ;

    St r i ng i ni t i al =conf i g. get I ni t Paramet er( " i ni t i al " ) ;try{c=I nt eger . parseI nt ( i ni t i al ) ;

    } cat ch( Number Format Except i on e) {c=0; }}publ i c voi d doGet ( Ht t pSer vl etRequest r eq, Ht t pSer vl etResponse

    res)t hr ows Ser vl et Except i on, I OExcept i on{

    r es. set Cont ent Type( "t ext / ht ml ") ;Pr i nt Wr i t er out =r es. get Wr i t er ( ) ;c=c+2;out . pr i nt l n( "Next Number i s : "+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 i ni t ( ) method of servlet must always call the i ni t ( ) method of superclass with

    the Ser vl et Conf i gobject that it has received. Let us understand why this is necessary.

    The Ser vl et Conf i gobject is available to the i ni t ( ) method. But what happens if any

  • 8/13/2019 Jee Servlets

    18/34

    Advanced Programming Using Java Distributed Programming with Java

    other method of the servlet needs it. Therefore, the i ni t ( ) method invokes the i ni t ( )

    method of superclass Ht t pSer vl et which is extended from Gener i cSer vl et . The

    Gener i cSer vl et class implements Ser vl et Conf i g class itself. Thus the config

    object can be reused by a servlet by invoking method to itself. This means that instead of

    sayingSt r i ng i ni t i al =conf i g. get I ni t Paramet er( i ni t i al ) ;

    one can say,St r i ng i ni t i al =get I ni t Paramet er( i ni t i al ) ;

    Thus, the value of initialisation parameter initial is accessed by

    get I ni t Par amet er ( ) method. Since any parameter that is accepted is String type, it is

    converted to integer type using par seI nt ( ) 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:servl et . count 2pl us. code=Countser vl et . count 2pl us. i ni t Ar gs=\

    i ni t i al =10

    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 linespecifies 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 asht t p: / / l ocal host : 8080/ ser vl et / count 2pl us

    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

  • 8/13/2019 Jee Servlets

    19/34

    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

  • 8/13/2019 Jee Servlets

    20/34

    Advanced Programming Using Java Distributed Programming with Java

    6.4.7 Some important Servlet MethodsGiven below is the list of some important Servlet methods with their description. All of

    these methods belong HttpServletRequest class.

    Method Description

    getServerName() Returns the host name of the server that received the requestgetProtocol() Returns the protocol and version

    getServerPort() Returns the port at which the request was received

    getMethod() Returns the method that invoked the servlet (POST, GET, etc.)

    getPathInfo() Gets any optional extra path information following the servlet path of

    this request's URI, but immediately preceding its query string.

    getPathTranslated() 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.

    getServletPath() Gets the part of this request's URI that refers to the servlet being

    invoked.

    getRealPath() Applies alias rules to the specified virtual path and returns the

    corresponding real path, or null if the translation can not beperformed for any reason.

    getQueryString() Gets any query string that is part of the HTTP request URL.

    getRemoteHost() Gets the hostname of the user making this request

    getRemoteAddr() Gets the IP address of the user making this request

    getRemoteUser() Gets the name of the user making this request

    getContentType() Returns the Internet Media Type of the request entity data, or null if

    not known.

    getContentLength() Returns the size of the request entity data, or -1 if not known.

    The following methods can be invoked on Ser vl et Conf i gobject.

    Method DescriptiongetInitParameterNames() Returns an Enumeration containing names of all initialisation

    parameters

    getInitParameter(name) 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 get Ser vl et Cont ext( ) and is written in the same

    way as the get Appl etCont ext ( ) method.

    6.4.8 Communication between Applets and ServletsLet us now see how a client applet calls a servlet. A client applet creates a URL for theservlet 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 ofrequest 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.

  • 8/13/2019 Jee Servlets

    21/34

    Advanced Programming Using Java Distributed Programming with Java

    The servlet, on the other hand receives this data via Ht t pServl etRequest object,

    processes the request and sends the result back via Ht t pServl etResponseobject. 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 andinvoked 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 servletexists. 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 User Dat abasePr oxy class. The definition of St ar t Database,

    User Dat a, User Dat abase, and User Dat abaseI mpl class remain the same.

    i mpor t j ava. i o. *;i mpor t j ava. net . *;

    i mport j ava. ut i l . * ;

    publ i c cl ass UserDatabasePr oxy{

    URL ser vl et ; / / The URL t o t he cal l ed ser vl et .Obj ect I nput St r eam i n; / / I nput str eam f romt he ser vl et .I nt eger code; / / Code f or t he oper at i on t o be

    per f ormed

    publ i c User Dat abaseProxy( URL web){

    try{servl et = new URL( web, " ser vl et / Dat abaseSer vl et " ) ;

    } cat ch ( Mal f ormedURLExcept i on e) {}}

    / / Adds a user t o t he dat abasepubl i c St r i ng cr eat eUser ( UserDat a data) t hr ows Except i on{

    code=new I nt eger( 2) ;Ser i al i zabl e obj s[ ] = {code, dat a };i n = post Obj ect s( ser vl et , obj s) ;St r i ng i d = ( St r i ng) i n. r eadObj ect( ) ;i n. cl ose( ) ;r et ur n i d;

    }

    / / Modi f i es a user i n t he dat abasepubl i c voi d edi t User ( St r i ng user i d, User Dat a dat a) t hr ows

    Except i on{

    code=new I nt eger( 3) ;Ser i al i zabl e obj s[ ] = { code, user i d, dat a };

  • 8/13/2019 Jee Servlets

    22/34

    Advanced Programming Using Java Distributed Programming with Java

    i n = post Obj ect s( ser vl et , obj s) ;i n. cl ose( ) ;

    }

    / / Del et es a user f r om t he dat basepubl i c voi d del et eUser ( St r i ng user i d) t hr ows Except i on{

    code=new I nt eger( 4) ;Ser i al i zabl e obj s[ ] = { code, user i d };i n = post Obj ect s( ser vl et , obj s) ;i n. cl ose( ) ;

    }

    / / Get s a user f r om t he dat basepubl i c User Dat a get User( St r i ng user i d) t hr ows Except i on{

    code=new I nt eger( 1) ;Ser i al i zabl e obj s[ ] = { code, user i d };i n = post Obj ect s( ser vl et , obj s) ;

    UserData data = ( UserDat a) i n. r eadObj ect ( ) ;i n. cl ose( ) ;r et ur n dat a;

    }

    / / Li st s a user f r om t he dat basepubl i c Hasht abl e l i st User s( ) t hr ows Except i on{

    code=new I nt eger( 0) ;Ser i al i zabl e obj s[ ] = { code };i n = post Obj ect s( ser vl et , obj s) ;Hasht abl e dat abase = ( Hasht abl e) i n. r eadObj ect ( ) ;i n. cl ose( ) ;r et ur n dat abase;

    }

    st at i c publ i c Obj ect I nput St r eam post Obj ect s( URL ser vl et ,Ser i al i zabl e obj s[ ] ) t hr ows Except i on

    {URLConnect i on con = servl et . openConnect i on( ) ;con. set DoI nput ( t r ue) ;con. setDoOut put ( t r ue) ;con. set Request Pr oper t y( "Cont ent - Type" , "appl i cat i on/ x-

    www- f orm- ur l encoded" ) ;

    / / Wr i t e t he ar gument s as post dataObj ect Out put St r eam out = new Obj ect Output St r eam(

    con. get Out put St r eam( ) ) ;i nt numObj ect s = obj s. l engt h;f or ( i nt x = 0; x < numObj ect s; x++) {

    out . wr i t eObj ect( obj s[ x] ) ;}out . f l ush( ) ;out . cl ose( ) ;

  • 8/13/2019 Jee Servlets

    23/34

    Advanced Programming Using Java Distributed Programming with Java

    r etur n new Obj ect I nput St r eam( con. get I nput St r eam( ) ) ;}

    }

    Listing 6.13 Code for proxy object (UserDatabaseProxy.java)

    This User Dat abasePr oxy 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 wewill write to call the remote object is Dat abaseServl et . Thus a new URL is created

    with / ser vl et / Dat abaseSer vl et 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 handlethe 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 givenbelow:

    LIST 0GET 1CREATE 2

    EDIT 3

    DELETE 4

    In each of these methods, an array of Ser i al i zabl eobjects and the servlet URL is sent

    to a method called post Obj ect s( ) . The contents of the Ser i al i zabl earray differ in

    each method. In case of creating a user a code, and a User Dat aobject is sent whereas in

    case of editing a user details a code, a User Dat aobject 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 post Obj ect s( ) method opens the connection to the URL and allows the

    connection to accept input and give output with the help of set DoI nput ( ) and

    set DoOut put ( ) methods. It also sets the servlets request objects content type property

    as appl i cat i on/ x- www- f or m- ur l encodewith the help of the following command:con. setRequest Pr oper t y( "Cont ent - Type" , "appl i cat i on/ x- www- f or m-ur l encoded" ) ;

    Setting a content type like this ensures that the servlets doPost ( ) method will be

    called. Then it gets the output stream from the URLConnect i onobject, this is the output

    stream for the servlet. The post Obj ect s( ) method then writes each serialized object

    that it had accepted via this output stream to the servlet. The servlet receives these objectsvia 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

    Dat abaseServl et (refer to program listing 6.14)

  • 8/13/2019 Jee Servlets

    24/34

    Advanced Programming Using Java Distributed Programming with Java

    i mpor t j ava. i o. *;i mpor t j ava. r mi . *;i mport j ava. ut i l . * ;i mpor t j avax. ser vl et . *;i mpor t j avax. ser vl et . ht t p. *;

    publ i c cl ass Dat abaseSer vl et extends Ht t pSer vl et{

    St r i ng r egi st r y; / / The pat h t o t he RMI r egi st r yUser Database db; / / The database access obj ect

    publ i c voi d i ni t ( Ser vl et Conf i g conf i g) t hr owsSer vl et Except i on

    {super . i ni t ( conf i g) ;r egi st r y = conf i g. get I ni t Par amet er ( "r egi st r y") ;i f ( regi str y == nul l ) r egi str y = "/ / l ocal host" ;t r y {

    St r i ng name = r egi st r y + " / DB1" ;db = ( User Dat abase) Nami ng. l ookup(name) ;} cat ch ( Except i on e) {

    e. pr i nt St ackTr ace( ) ;}

    }publ i c voi d doPost ( Ht t pSer vl et Request r eq,

    Ht t pSer vl et Response r esp) t hr ows Ser vl et Except i on,I OExcept i on

    {/ / Open t he I / O st r eamsObj ect I nput St r eam i n = new Obj ect I nput St r eam( r eq.

    get I nput St r eam( ) ) ;Obj ect Out put St r eam out = new Obj ect Out put St r eam( r esp.get Out put St r eam( ) ) ;

    t r y {/ / Fi nd out whi ch oper at i onI nt eger codeI nt =( I nt eger ) i n. r eadObj ect ( ) ;i nt code=codeI nt . i nt Val ue( ) ;Syst em. out . pr i nt l n( code) ;i f ( code==0) {

    Hasht abl e dat abase = db. l i st User s( ) ;out . wr i t eObj ect ( dat abase) ;

    }el se i f ( code==1) {

    St r i ng i d=( St r i ng) i n. r eadObj ect( ) ;UserData data=db. getUser ( i d) ;out . wr i t eObj ect ( dat a) ;

    }el se i f ( code==2) {

    UserData data=( UserData) i n. r eadObj ect ( ) ;St r i ng i d=db. creat eUser ( dat a) ;out . wr i t eObj ect( i d) ;

  • 8/13/2019 Jee Servlets

    25/34

    Advanced Programming Using Java Distributed Programming with Java

    }el se i f ( code==3) {

    St r i ng i d=( St r i ng) i n. r eadObj ect( ) ;UserData data=( UserData) i n. r eadObj ect ( ) ;db. edi t User ( i d, dat a) ;

    }el se i f ( code==4) {

    St r i ng i d=( St r i ng) i n. r eadObj ect( ) ;db. del et eUser ( i d) ;

    }} cat ch ( Except i on e) { e. pr i nt St ackTr ace( ) ; }

    / / Cl ose t he I / O st r eamsi n. cl ose( ) ;out . cl ose( ) ;

    }}

    Listing 6.14 Code for the Servlet that in turn invokes the remote methods (DatabaseServlet.java)

    The Dat abaseServl et has two variables a String object called registrythat will hold

    the path of the registry running at the server, and a User Dat abaseobject called db. This

    object will be used to invoke the methods of remote object. The i ni t ( ) 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 l ocal host 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 r eadObj ect ( ) 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 l i s tUsers( ) method of the remote object is made which

    returns a Hasht abl eobject. This object is written to the output stream retrieved from

    the response object. If the code is 1, a call to the get User ( ) method is made. But this

    method requires the id of the user, which is sent to the servlet (refer to

    User Dat abasePr oxyclasss get User ( ) method, along with code id was also sent).

    Thus, r eadObj ect ( ) method is used to retrieve the user id from the input stream and

    the id that is received is supplied to the get User ( ) method of the remote object. This

    method returns a User Dat aobject, which is again written to the output stream receivedfrom 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:St r i ng host = t hi s. get CodeBase( ) . get Host ( ) ;St r i ng name = " / / " + host + " / DB1" ;

  • 8/13/2019 Jee Servlets

    26/34

    Advanced Programming Using Java Distributed Programming with Java

    db = ( User Database) j ava. r mi . Nami ng. l ookup( name) ;

    write these two statements:URL servl et Base = new URL( "ht t p: / / l ocal host : 8080" ) ;db = new User Dat abaseProxy( ser vl et Base) ;

    Compile all programs and run the ser vl et r unner utility in a separate dos prompt

    window, the St ar t Database class in separate command window and the

    appl et vi ewer in the third command window.

    6.4Case 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 databaseproxy 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 User Dat abaseclass. This is the remote interface forthe remote object.

    package col l ege. st udent ;

    publ i c i nt erf ace UserDat abase ext ends j ava. r mi . Remote{

    publ i c St r i ng pr ocessAppl i cat i on( Appl i cat i on appl ) t hr owsj ava. r mi . Remot eExcept i on;

    }

    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 pr ocessAppl i cat i on( ) method accepts an Appl i cat i on

    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 UserDatabaseI mpl . j ava.

    package col l ege. st udent ;

    i mpor t j ava. r mi . *;

    i mpor t j ava. r mi . ser ver . *;

    publ i c cl ass UserDatabaseI mpl ext endsj ava. r mi . ser ver . Uni cast Remot eObj ect i mpl ements User Dat abase{

    st at i c Cour se cs[ ] = new Cour se[ 3] ;

    publ i c UserDat abaseI mpl ( ) t hr ows j ava. r mi . RemoteExcept i on

  • 8/13/2019 Jee Servlets

    27/34

    Advanced Programming Using Java Distributed Programming with Java

    {St r i ng st r Cor esub[ ] = {"c", "c++" , "ooads" ,

    "Net wor ki ng", "Or acl e", "vc", "uni x", "vb"};St r i ng st r Opt sub[ ] = {"NT" , " J AVA" , "SQL"};

    cs[ 0] =cr eat eCour se( "MDMC" , st r Coresub, st r Opt sub) ;cs[ 0] . set Ent r anceQual ( new Long( 75) ) ;

    cs[ 0] . set MaxSt udent s( 5) ;

    St r i ng st r Cor e2[ ] = {"uni x", "c" , "ooads"};St r i ng st r Opt 2[ ] = {"DBA" , "C++"};cs[ 1] =cr eat eCour se("UCO" , st r Cor e2, st r Opt 2) ;cs[ 1] . set Ent r anceQual ( new Long( 75) ) ;cs[ 1] . set MaxSt udent s( 5) ;

    St r i ng st r Core3[ ] = {"c++"};St r i ng st r Opt 3[ ] = {"OOADS" , " J AVA"};cs[ 2] =cr eat eCour se("C++" , st r Cor e3, st r Opt 3) ;cs[ 2] . set Ent r anceQual ( new Long( 75) ) ;

    cs[ 2] . set MaxSt udent s( 5) ;}

    publ i c st at i c Cour se cr eat eCour se(St r i ng st r Name, St r i ngstr Cor e[ ] , St r i ng st r Opt [ ] ) {Cor eSubj ect cor e[ ] = new Cor eSubj ect [ st r Cor e. l engt h] ;f or ( i nt i =0; i

  • 8/13/2019 Jee Servlets

    28/34

    Advanced Programming Using Java Distributed Programming with Java

    {message1 = "Sor r y! St udent i s not enr ol l ed" ;

    }r et urn message1;

    }}

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

    You are already familiar with the logic of the program. The User Dat abaseI mpl class

    implements the pr ocessAppl i cat i on( ) method and returns Congrat s! The

    st udent i s sel ect ed if the student has more than 75% marks and there is a seat

    available in the batch, otherwise it returns a message Sor r y! The st udent i s not

    enr ol l ed.

    Next we will see the implementation of the proxy object that the client will use to

    communicate with the server. This class is called User Dat abasePr oxy. Program listing

    6.17 given below shows the definition of this file.

    package col l ege. st udent ;

    i mpor t j ava. i o. *;i mpor t j ava. net . *;i mport j ava. ut i l . * ;publ i c cl ass UserDatabasePr oxy{

    URL ser vl et ; / / The f ul l y- qual i f i ed URL t o t he cal l edservl et .

    URL webBase; / / The compl et e URL t o t he ser vl et web ser ver( ex. ' ht t p: / / www. sun. com: 8080' ) .

    Obj ect I nput St r eam i n; / / I nput str eam f romt he ser vl et .

    publ i c User Dat abaseProxy( URL web){

    webBase = web;}publ i c St r i ng pr ocessAppl i cat i on( Appl i cat i on appl 1) t hr ows

    Except i on{

    servl et = new URL( webBase, " servl et / DatabaseServl et" ) ;Ser i al i zabl e obj s[ ] = { appl 1 };

    i n = Ser vl et Wr i t er . post Obj ects( ser vl et , obj s) ;St r i ng i d = ( St r i ng) i n. r eadObj ect( ) ;i n. cl ose( ) ;retur n i d;

    }}

    Listing 6.17 The proxy object (UserDatabaseProxy.Java)

    The UserDatabaseProxy class declares two variables webBasethat will store the logicalpath where the servlet is located and servletthat will store the full path to the servlet. The

  • 8/13/2019 Jee Servlets

    29/34

    Advanced Programming Using Java Distributed Programming with Java

    constructor method of this class accepts a logical path to the servlet and initialises

    webBasewith that value. The pr ocessAppl i cat i on( ) method of this class accepts an

    Appl i cat i onobject, initialises servletwith the full path to the servlet, creates an array

    of Serializable elements, and stores Application object in it. It then calls the

    post Obj ect s( ) method of Ser vl et Wr i t er 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 Ser vl et Wr i t er 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 Ser vl et Wr i t er class is

    given in program listing 6.18.

    package col l ege. st udent ;i mpor t j ava. net . *;i mpor t j ava. i o. *;

    publ i c cl ass Ser vl et Wr i t er {st at i c publ i c Obj ect I nput St r eam post Obj ect s( URL ser vl et ,

    Ser i al i zabl e obj s[ ] ) t hr ows Except i on{

    URLConnect i on con = ser vl et . openConnect i on( ) ;con. set DoI nput ( t r ue) ;con. set DoOut put ( t r ue) ;con. set UseCaches( f al se) ;con. set Request Pr oper t y( "Cont ent - Type" , "appl i cat i on/ x-

    www- f orm- ur l encoded" ) ;

    / / Wr i t e t he ar gument s as post dataObj ect Out put St r eam out = new Obj ect Out put St r eam

    ( con. get Out put St r eam( ) ) ;

    i nt numObj ect s = obj s. l engt h;f or ( i nt x = 0; x < numObj ect s; x++) {

    out . wr i t eObj ect( obj s[ x] ) ;}out . f l ush( ) ;out . cl ose( ) ;Syst em. out . pr i nt l n( "Ser vl et Wr i t er ") ;r etur n new Obj ect I nput St r eam( con. get I nput St r eam( ) ) ;

    }}

    Listing 6.18 The ServletWriter class

    Now we will see the code for Dat abaseServl et class. This class will not be a part ofthe 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 Dat abaseServl et class.

    i mpor t j ava. i o. *;i mpor t j ava. r mi . *;i mport j ava. ut i l . * ;i mpor t j avax. ser vl et . *;

  • 8/13/2019 Jee Servlets

    30/34

    Advanced Programming Using Java Distributed Programming with Java

    i mpor t j avax. ser vl et . ht t p. *;i mpor t col l ege. st udent . *;

    publ i c cl ass Dat abaseSer vl et extends Ht t pSer vl et{

    St r i ng r egi st r y; / / The pat h t o t he RMI r egi st r yUser Database db; / / The database access obj ect

    publ i c voi d i ni t ( Ser vl et Conf i g conf i g) t hr owsSer vl et Except i on

    {super . i ni t ( conf i g) ;Syst em. out . pr i nt l n( "beg i ni t of ser vl et ") ;

    / / Get t he l ocat i on of t he RMI r egi st r y.r egi st r y = conf i g. get I ni t Par amet er ( "r egi st r y") ;

    / / I f undef i ned, assume t he l ocal hosti f ( regi str y == nul l ) r egi str y = "/ / l ocal host" ;

    t r y { / / Now get t he database obj ectSt r i ng name = r egi st r y + " / DB1" ;db = ( User Dat abase) Nami ng. l ookup(name) ;

    } cat ch ( Except i on e) {e. pr i nt St ackTr ace( ) ;

    }}

    publ i c voi d doPost ( Ht t pSer vl et Request r eq,Ht t pSer vl et Response r esp) t hr ows Ser vl et Except i on,I OExcept i on

    {Obj ect I nput St r eam i n = new Obj ect I nput St r eam

    ( r eq. get I nput St r eam( ) ) ;Obj ect Out put St r eam out = new Obj ect Out put St r eam

    ( r esp. get Out put St r eam( ) ) ;t r y {

    Appl i cat i on appl 1 = ( Appl i cat i on) i n. r eadObj ect ( ) ;Syst em. out . pr i nt l n( "got Appl obj ect ") ;St r i ng message1 = db. pr ocessAppl i cat i on( appl 1) ;Syst em. out . pr i nt l n( "Processed") ;out . wr i t eObj ect ( message1) ;

    } cat ch ( Except i on e) { e. pr i nt St ackTr ace( ) ; }/ / Cl ose t he I / O st r eams

    i n. cl ose( ) ;out . cl ose( ) ;

    }}

    Listing 6.19 The DatabaseServlet class

  • 8/13/2019 Jee Servlets

    31/34

    Advanced Programming Using Java Distributed Programming with Java

    The Dat abaseServl et receives the arguments via its request objects input stream and

    calls the pr ocessAppl i cat i on( ) 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

    St ar t Dat abase. j ava

    package col l ege. st udent ;i mpor t j ava. r mi . *;i mpor t j ava. r mi . regi str y. *;i mpor t j ava. i o. *;i mport j ava. ut i l . * ;i mpor t j ava. net . *;publ i c cl ass St ar t Dat abase{

    publ i c St ar t Dat abase( ){

    t r y { / / St ar t up t he r egi st r yRegi st r y reg = j ava. r mi . r egi st r y. Locat eRegi st r y.

    creat eRegi st r y(1099) ;/ / Cr eat e t he Dat abase obj ectUser Dat abaseI mpl db = new User Dat abaseI mpl ( ) ;/ / Bi nd i t t o t he r egi str yNami ng. r ebi nd( "DB1" , db) ;

    } cat ch ( j ava. r mi . UnknownHost Except i on unx) {unx. pr i nt St ackTr ace( ) ;

    } cat ch ( j ava. r mi . Remot eExcept i on r ex) {r ex. pr i nt St ackTr ace( ) ;

    } catch ( j ava. net . Mal f ormedURLExcept i on mf x) {

    mf x. pr i nt St ackTr ace( ) ;}

    }st at i c publ i c voi d mai n( St r i ng ar gs[ ] ){

    Syst em. set Secur i t yManager( new RMI Secur i t yManager ( ) ) ;St ar t Database st art er = new St art Dat abase( ) ;

    }}

    Listing 6.20 The StartDatabase class

  • 8/13/2019 Jee Servlets

    32/34

    Advanced Programming Using Java Distributed Programming with Java

    SUMMARY

    Client/Server systems have three components the user interface layer, theinformation processing layer and the information storage layer.

    The information processing layer may reside on either the client or the servermachine.

    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 areorganized as cells.

    DCOM is an extension of COM, which makes it possible for a COM object on onemachine to interact with another COM object on a remote machine.

    DCOM provides very good security features and is object oriented (in contrast toDCE that is procedure oriented) but it does not give good performance on non-

    Windows platform.

    CORBA provides an excellent framework for designing distributed applications. InCORBA 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 ofsoftware vendors, and both server and client can be distributed in CORBA.

    RMI is Javas answer to designing distributed applications that supports seamlessremote 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 remoteinterface. 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 thesemethod calls to the remote reference layer. The remote reference layer on the clientmachine interacts with the remote reference layer on the server machine, which inturn 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 supportRMI fully, which makes is impossible for IE and Netscape users t use RMI applets.

  • 8/13/2019 Jee Servlets

    33/34

    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 startingonly one process for a particular CGI script. But in case of concurrent calls for thesame CGI script, separate processes are created.

    Server extensions differ from CGI and FastCGI in terms of how they run. CGI andFastCGI run as external applications and therefore are not able to make use of

    servers capabilities. Server extensions run inside the server and can take theadvantage 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, theybecome 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 andservice() method needs to be overridden in case of generic servlets.

    The service() method of HttpServlet class automatically send the requests to eitherdoGet(), doPost(), or doHead(), etc. methods depending on the type of the call. ThedoHead() 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 getthe initialisation parameters of the servlet.

  • 8/13/2019 Jee Servlets

    34/34

    Advanced Programming Using Java Distributed Programming with Java

    The initialisation parameters can be passed to the servlet via the properties file andcan 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