2. Distributed Objects and Remote Invocation by L9paT0cR

VIEWS: 0 PAGES: 93

									2. Distributed Objects
and Remote Invocation
  Chapter 2.5 and 2.6




          Design of Distributed Software
    Distributed Software Technologies
 SUN Remote Procedure Call (RPC)
 JAVA Remote Method Invocation (RMI)
 Common Object Request Broker Architecture
  (CORBA)
 Web Centric Architecture
        Servlets
        Java Server Pages (JSP)
        Enterprise Java Beans (EJB)
 Web Services
 .Net Remoting



         Design of Distributed Software       2
       Schema ODS
ODS - Ontwerp van geDistribueerde Software

Week 1 - 23/09                VM Intro (Bart)

Week 2 - 30/09                VM Vervolg intro + RMI Hfdst2 1.-4. (Bart)                     NM Vervolg Hfdst 2 (Filip) (Aud. Zuiderpoort)

Week 3 - 07/10                VM Hfstk 3 - part 1 (Filip)

Week 4 - 14/10                VM Hfstk 3 - part 2 (Filip)                                    Lab Sessie 1 CORBA/RMI *

Week 5 - 21/10                VM Hfstk 4 (Bart)                                              Lab Sessie 2 Web Centric *

Week 6 - 28/10                VM Hfstk 5 (Bart)                                              Lab Sessie 3 Web Services *

Week 7 - 04/11                VM Hfstk 6+9 (Filip)                                           Project Sessie 1 *

Week 8 - 11/11 = verlof       ////////////////////////////////////////////////////////////   /////////////////////////////////////////////////////////////

Week 9 - 18/11                VM Hfstk 7+8 (Bart)                                            Project Sessie 2 *

Week 10 - 25/11               Project Sessie 3 (groep A) *                                   Project Sessie 3 (groep B) *

Week 11 - 02/12               VM Hfdstk 10 (Filip)                                           ,

Week 12 - 09/12               ,                                                              Feedback




                 Design of Distributed Software                                                                                                              3
2.5 CORBA : Common Object
Request Broker Architecture




        Design of Distributed Software
   2.5 Outline
                               Introduction + Motivation

                                    Corba Framework

Basic Architecture                Corba Object Model         Corba Object Refs


                                  Basic Corba Example

 Corba Implemen-                          Advanced         Portable Object Adapter
     tations                             Architecture


                               Extended Corba Example




        Design of Distributed Software                                           5
    Situating CORBA
   Socket Interface:
       no concept of methods, objects
       no services:
            Binding service, Activation Service, Persistent object storage
             service, Object location service, Transaction service, Event service
       support for multiple programming languages

   JAVA RMI/ C RPC
       concept of methods, objects
       services:
            Binding service, Activation Service, “light” Persistent object storage
             service
       single programming language

        Design of Distributed Software                                                6
    CORBA: Basic Idea

           Need for middleware that allows applications
        to communicate irrespective of their programming
           language and that offers all required services

   Recognized by OMG in 1989
       OMG = Object Management Group
       Industry Group of over 800 participants
       Their goal : design middleware that allows applications
        to communicate irrespective of (i) their programming
        language, (ii) their hardware and software platforms
        and (iii) the networks they communicate over.


          Design of Distributed Software                          7
    CORBA ORB
   OMG introduced ORB
       ORB = Object Request Broker
       Software component which helps a client to invoke a
        method on an object

   Timeline :




        Design of Distributed Software                        8
    CORBA framework components
 IDL = Interface Definition Language
 CORBA Architecture
       ORB Core, Object Adapter, Skeletons, Client
        stubs/proxies, Implementation repository, Interface
        repository, Dynamic Invocation Interface, Dynamic
        Skeleton Interface
   GIOP = General Inter-Orb protocol
       CDR = Common Data Representation
   Object Reference Definition
       IOR = Interoperable Object Reference
   CORBA Services
       Naming, Event, Notification, Security, Transaction,
        Concurrency, Trading
        Design of Distributed Software                        9
     RMI : architecture


            a        proxy_b
                                                    dispatcher    skeleton        b

        Remote Ref. Mod.
                                                                       Remote Ref. Mod.

                 communication
                                                             communication

                client                                           server
• proxy                                              • dispatcher
     • 1 proxy per remote object                          • typically 1 per class
     • local representative of remote object              • identify message to invoke in skeleton
     • implements all methods of remote interface    • skeleton
     • handles (un)marshalling                            • typically 1 per class
            Remote Ref Module :                           • (un)marshalling
            •remote object reference table                • invokes method on remote object
            • table Distributed Software
           Design of of local proxies                     • sends reply                      10
     CORBA : architecture


        a         proxy_b
                                                     Object
                                                  dispatcher
                                                    Adapter
                                                                   skeleton       b


                ORB Core                                       ORB Core

             client                                             server
• ORB Core
    • cfr Communication Module                  • Object Adapter
    • Provides interface:                            • Remote Ref + Dispatcher
          • start/stop ORB                           • creates remote object references
          • convert between remote                     for CORBA objects
            objects and strings                      • dispatches each invocation to
          • provide argument lists for                 the appropriate servant
            requests using dynamic invocation        • activates objects
            Design of Distributed Software           • Portable Object Adapters = POAs11
    CORBA architecture (2)
   Skeletons
       generated by IDL compiler
       remote method invocations are dispatched via
        appropriate skeleton to a particular servant
       unmarshals the arguments
       marshals exceptions and results
   Client Stubs/proxies
       generated by IDL compiler
       marshals the arguments
       unmarhals exceptions and results




        Design of Distributed Software                 12
    CORBA RMI : Object Model
   CORBA’s object model :



             A                         B      C     D                E


   Differences with Java RMI :
       Clients are not necessarily objects
       CORBA object:
          implements an IDL interface
          has a remote object reference
          able to respond to invocations of methods on its IDL interface
       No class objects in CORBA
       Data structures of various types and complexity can be passed as
        arguments


             Design of Distributed Software                                 13
CORBA Objects



                                    data

    A                               Method 1
                                    Method 2
                                    Method 3
 Client



                                           CORBA
                                           Object
   Design of Distributed Software                   14
      CORBA IDL interface example
             #ifndef __ECHO_IDL__
             #define __ECHO_IDL__


               /**
echo.idl :      * The Echo interface which is basically an interface that contains an echo
             operation and an accompanying operation.
                * @author AT&T omniORB, adapted by Filip De Turck
                * @version $Revision: 1.6 $, $Date: 2001/06/26 00:26:46 $
              **/
               interface echo {
                    /**
                     * Echoes the string received
                     * @param mesg The received string which has to be echoed
                     * @return The echoed string, which has to be <U>freed by the caller</U>
                     **/
                    string echoString(in string mesg);
                    /**
                    * @return The number of times the <code> echoString </code> operation is called
                     **/
                    long   times_called();
               };
             Design of Distributed Software                                                           15
             #endif
    CORBA RMI : IDL
   CORBA IDL
       IDL interface specifies a name and a set of methods
        that clients can request
       Parameters and results: in, out, inout keywords
       Passing CORBA objects, primitive and constructed
        types
       Type Object: common supertype of all IDL interface
        types
       Exceptions: defined in interfaces and thrown by their
        methods
       Invocation semantics: at-most-once
            maybe semantics by oneway keyword




        Design of Distributed Software                          16
        CORBA RMI : pseudo objects
   CORBA implementations provide some interfaces
    to the functionality of the ORB
       pseudo objects:
            Cannot be passed as arguments
            IDL interface
            Implemented as libraries


   Example: ORB interface
       represents the functionality that programmers need to
        access:
            init method : to initialize the ORB
            connect method : to register CORBA objects with the ORB
            shutdown method : to stop CORBA objects
            conversion between remote object references and strings

             Design of Distributed Software                            17
    CORBA client and server example

   IDL compiler :                              Java Interface files
                                                    echo.java

                                                Server Skeletons
                                                 _echoImplBase.java
      *.idl                 IDL compiler        Proxy Classes or
      files                     (idlj)             Client Stubs
                                                  _echoStub.java
                                                  Java classes
     echo.idl                                       for structs

                                                   Helper and
                                                  Holder classes
           $ idlj -fall –oldImplBase echo.idl     echoHelper.java
       Design of Distributed Software                                  18
 Java interface file
/**
* echo.java .
* Generated by the IDL-to-Java compiler
* from echo.idl
*/

public interface echo extends org.omg.CORBA.Object
{
  public String echoString(String mesg);
  public int times_called();
} // interface Echo




     Design of Distributed Software                  19
    Servant Class Implementation
import org.omg.CORBA.*;
class echoServant extends _echoImplBase {
   private ORB theORB;
   private int counter;

     public echoServant(ORB orb) {
        theOrb = orb;
        counter = 0;
     }

     public String echoString(String mesg) {
        counter++;
        String p = mesg;
        return p;
     }

     public int times_called() {
        return counter;
     }
}



       Design of Distributed Software          20
    Servant Classes
 Extends the corresponding skeleton class
 Implements the interface methods
 Uses the method signatures defined in the
  equivalent Java interface
 ORB private attribute: to connect new CORBA
  objects to the ORB (connect method) or
  shutdown objects (shutdown method)




      Design of Distributed Software            21
  Server Class Implementation
import org.omg.CORBA.*;

public class echoServer
{
    public static void main(String args[]) throws
         org.omg.CORBA.UserException {
         try{
             java.util.Properties props = System.getProperties();
             ORB orb = ORB.init(args, props);
             echoServant echoRef = new echoServant(orb);
             orb.connect(echoRef);

             System.out.println(“echoServer ready and waiting ...");
            orb.run();
         } catch (Exception e) {
            System.err.println("ERROR: " + e);
            e.printStackTrace(System.out);
        }
        System.out.println(“Echo Server Exiting...");

    } //main
} // class




       Design of Distributed Software                                  22
    CORBA server
   Java class with Main method
   Creates and initializes the ORB
   Creates an instance of Servant class
   Registers it to the ORB (through the connect
    method)
   Waits for incoming client requests




      Design of Distributed Software               23
    Client Implementation
import org.omg.CORBA.*;

public class echoClient
{
    public static void main(String args[])

      java.util.Properties props = System.getProperties();
      org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, props);

      if (args.length == 0) {
           System.err.println("usage: java echoClient <object reference>\n");
           System.exit(1);}

      try {
        org.omg.CORBA.Object obj = orb.string_to_object(args[0]);
        if (obj==null) {
          System.err.println("Got a nil reference.\n"); System.exit(1);}
        Echo echoRef = echoHelper.narrow(obj);
        String src = "Hello!";
        String answer = echoRef.echoString(src);

        System.out.println("I said:\""+src+"\"."+
                      " The Object said:\""+answer+"\“.");

        System.out.println("The function echoString on the object is called already "+
                        echoRef.times_called()+" time(s)");

      } catch(Exception ex) {
        System.err.println("Caught an exception!!.\n");
      }

      orb.destroy();
      System.exit(0);
   } //mainDesign of Distributed Software                                                24
} // class
    Client Program
 Creates and initializes the ORB
 Narrow method to cast Object to particular
  required type
 Invokes the methods


   Catch CORBA System exceptions

   Objects cannot be passed by value in CORBA




      Design of Distributed Software             25
    Running the server and client
   Start orbd :
        UNIX command shell : $ orbd
        MS-DOS system prompt : start orbd
   Start the Echo server :
        UNIX command shell :
          $ java echoServer
        MS-DOS system prompt :
          start java echoServer
        Result: echoServer ready and waiting ...
   Run the client application :
        $ java echoClient ior_server
        ResuIt: I said: “Hello!“. The Object said: “Hello!“.



         Design of Distributed Software                         26
   Chapter Outline
                               Introduction + Motivation

                                    Corba Framework

Basic Architecture                Corba Object Model         Corba Object Refs


                                  Basic Corba Example

 Corba Implemen-                          Advanced         Portable Object Adapter
     tations                             Architecture


                               Extended Corba Example




        Design of Distributed Software                                        27
    CORBA implementations
   Interesting URLs :

       http://cmeerw.org/freeorbwatch

       http://dmoz.org/Computers/Programming/
        Component_Frameworks/CORBA/
        Object_Request_Brokers/

       http://java.sun.com/developer/
        onlineTraining/corba/corba.html

       http://java.sun.com/j2se/1.5.0/docs/
        guide/idl/index.html

         Design of Distributed Software          28
     Portable Object Adapter

                                                 object adapter : connects a
   Object
dispatcher
  Adapter       skeleton   b                       request using an object
                                                  reference with the proper
             ORB Core                            code to service that request
              server


Portable Object Adapter (POA):
 Allow programmers to construct object implementations
  that are portable between different ORB products.
 Allow a single servant to support multiple object identities
  simultaneously.



                Design of Distributed Software                                  29
    Example: Echo Servant with POA
import org.omg.CORBA.*;
import org.omg.PortableServer.POA;

class echoServant extends echoPOA {
   private ORB theOrb;
   private int counter;

    public echoServant(ORB orb) {
         theOrb = orb;
         counter = 0;
    }

    public String echoString(String mesg) {
         counter++;
         String p = mesg;
         return p;
    }

    public int times_called() {
         return counter;
    }
}




       Design of Distributed Software         30
       Example: Echo Server with POA
import org.omg.CORBA.*;
Import org.omg.PortableServer.*;

public class echoServer
{
    public static void main(String args[]) throws org.omg.CORBA.UserException {
          try{
             // create and initialize the ORB
             ORB orb = ORB.init(args, null);

              // get reference to rootpoa
              POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));

               // create servant and register it with the ORB
                echoServant eS = new echoServant(orb);

               //activate the server object
               rootpoa.activate(echoServantRef);

               // get and narrow object reference from the servant
               org.omg.CORBA.Object ref = rootpoa.servant_to_reference(eS);
               echo echoRef = echoHelper.narrow(ref);

              // wait for invocations from clients
              orb.run();

           } catch (Exception e) {
             System.err.println("ERROR: " + e);
             e.printStackTrace(System.out);
        }
        System.out.println(“Echo Server Exiting...");

     } //main
} // class
              Design of Distributed Software                                               31
  Server Implementation with POA
1. Get the root POA
     org.omg.CORBA.Object obj = orb.resolve_initial_references("RootPOA");
     POA rootpoa = POAHelper.narrow(obj);

2. Create the servant instance
     echoServant echoServantRef = new echoServant(orb);

3. Activate the server object
     rootpoa.activate(echoServantRef);

4. Create the object reference from the POA
     org.omg.CORBA.Object ref = rootpoa.servant_to_reference(echoServantRef);

5. Narrow the object reference
     echo echoRef = echoHelper.narrow(ref);

6. Wait for incoming requests from clients
     orb.run()




        Design of Distributed Software                                          32
    Interface Definition Language
   Additional keywords (compared to C++):

        interface, any, attribute, in, out, inout, readonly, raises

        module : group interfaces and idl types in logical units

   C++ preprocessing capabilities




         Design of Distributed Software                                33
    Interface Definition Language (2)
        IDL types: short, long, unsigned short, usigned long,
         float, double, char, boolean, octet, any
        const keyword
        Object = common supertype
        arrays or sequences in arguments : typedef !

   Attributes
        cfr public class fields in Java
        readonly : only getter method is provided


   Inheritance:
        multiple inheritance is allowed
        scoped names to make distinction between types
         Design of Distributed Software                          34
  More advanced IDL example:
Whiteboard.idl
struct Rectangle{                       struct GraphicalObject {
    long width;                            string type;
    long height;                           Rectangle enclosing;
    long x;                                boolean isFilled;
    long y;                             };
} ;

interface Shape {
   long getVersion() ;
   GraphicalObject getAllState() ; // returns state of the GraphicalObject
};

typedef sequence <Shape, 100> All;
interface ShapeList {
   exception FullException{ };
   Shape newShape(in GraphicalObject g) raises (FullException);
   All allShapes(); // returns sequence of remote object references
   long getVersion() ;
};


       Design of Distributed Software                                 35•
    IDL module

 Modules allow interfaces and associated
  definitions to be grouped.
 A module defines a naming scope.

             module Whiteboard {
                struct Rectangle{
                ...} ;
                struct GraphicalObject {
                ...};
                interface Shape {
                ...};
                typedef sequence <Shape, 100> All;
                interface ShapeList {
                ...};
             };
      Design of Distributed Software                 36
2.6 Invocations in JEE Architecture
         1.   Introduction
         2.   Servlets
         3.   Java Server Pages
         4.   Java Server Faces (JSF)
         5.   Apache Struts
         6.   Invocation of Enterprise Java Beans (EJB)
         7.   Ajax

         Design of Distributed Software
                                                        1. Introduction
 Web centric architectures

               HTTP request

    webclient
                                       webserver
              HTTP response

Thin client :
• web browser
• plug-ins

Advantages
• ubiquitous and uniform client
• no network blockages (firewalls) for HTTP (port 80)
• huge user base


      Design of Distributed Software                               38
                                                                            1. Introduction
    Protocol messages : HTTP
            Application level message formats and behavior
Request                                         Response
• GET (data encoded in URL)
                                                • REPLY
• POST (data encoded in message)
                                                • header
• header                                           • status (success/failure)
    • requested content (URL)                      • response data + MIME type
   • HTTP version                                  (Multipurpose Internet Mail Extensions)
   • response types accepted (MIME, language)
   • client browser
   • connection type
   • POST
         • content of request
         • content length


                  Stateless protocol
                  • 1 transaction for each request/response pair
                  • each request/response pair INDEPENDENT of others

          Design of Distributed Software                                               39
                                                                   1. Introduction
    Addressing resources : URL

<protocol>://<hostname>:<port>/<fully qualified pathname>?<parameters>
<protocol> : http, https, ftp, telnet, …
<hostname> : IP-address or DNS-name
<port> : port for webserver (default : http : 80, https: 343)
<fully qualified pathname> : directory + file name (default index.html)
<parameters> : normally used to specify (name, value)-pairs
        ? : separates resource name from parameters
        + : represents space
        & : separate (name,value) pairs
        = : binds value to name
        % : escape character
            followed by 2 hex-symbols representing ASCII value
                                                                  elections!

e.g. http://www.spy.cia.com:80/reports/interest?subject=elections%21

         Design of Distributed Software                                        40
                                                          1. Introduction
Standard interaction
                Retrieving a (HTML) document


                    HTTP GET

      webclient
                                    webserver
                  HTTP REPLY



Typical interactions
1. Connect : client opens connection with server
2. Request : client sends message to identify resource/service
3. Response : server sends message to respond to request
4. Disconnect : close client-server connection



   Design of Distributed Software                                    41
                                                           1. Introduction
Dynamic content : CGI
• Common Gateway Interface
• URL
    • specifies (small) program
    • gives input through URL-parameters
    • program generates html-output
      (or output for plug in)
                  HTTP POST
      webclient
                                     webserver
                  HTTP REPLY

                                  INVOKE

                                           CGI-program
• Performance/resource issues
    • new separate process for each request
    • programs often in scripting languages (e.g. Perl)
    • resources (e.g. database connections) created/destroyed per
      request
     Design of Distributed Software                                   42
                                                                         1. Introduction
 Dynamic content : HTML for CGI
 HTML <FORM>-tag
 • METHOD-field : specifies HTTP message type
 • ACTION-field : specifies URL (without parameters)
 • parameters specified in subsequent INPUT fields



<html>
<head>
<title> Personal ID </title>
</head>

<body>
<FORM METHOD="GET" ACTION="http://java.sun.com/prog/enter">
 <P>Enter first name <INPUT NAME="first"></INPUT></P>
 <P>Enter family name <INPUT NAME="family"></INPUT></P>
 <INPUT TYPE="submit“ VALUE=“Submit Query">
</FORM>
</body>
</html>                   http://java.sun.com/prog/enter?first=John+F.&family=Kennedy


        Design of Distributed Software                                              43
                                                                 1. Introduction
  Servlets and JSP
• Plug-in object at server side
• Runs separate thread per request
• Shares resources with other servlets
• Servlet life cycle managed by container process
        (single process, single JVM) :
        Created/destroyed/activated/passivated
                  HTTP POST
  webclient
                                          webserver
                 HTTP REPLY

                                        INVOKE

  webclient

                                             Servlet Container


       Design of Distributed Software                                       44
                                                                          1. Introduction
  Servlets and JSP
• Servlet disadvantage :
    • pages contain static + dynamic data
    • static data created dynamically -> not optimal
• Solution
    • mix static and dynamic code in single webpage
    • compile webpage to extract servlets and static portions
    • configure webserver to
         • automatically invoke servlets to create dynamic content
         • merge dynamic and static content to response to client

   JSP : Java Server Page
                                                       HTML
               passive                  JSP
                                        compiler
                                                       code
               active
              passive                              Servlet class

       Design of Distributed Software
                                                   Actually : JSP = Servlet          45
                                                                                         1. Introduction
  EJB
• Server side component technology to code application logic
    • model business logic
    • model business objects (“database record”)
                                                  Business tier            Persistent Storage tier
Client tier                      Web tier         Middle Tier              Entreprise Systems Tier



  webclient




                                                       Application logic
                                     webserver




                                 Servlet Engine



 Application
   client


         Design of Distributed Software                                                              46
                                                           1. Introduction
  EJB
• Session beans

    • Transient, DO NOT survive server shutdown
    • Associated with ONE client (at any given time)
    Stateless session beans
        • no state between successive invocations
    Stateful session beans
        • state info kept consistent between invocations

• Entity beans

    • Persistent, DO survive server shutdown
    • State persists method calls/server shutdown
    • Can be shared between multiple clients
    Container Managed Persistence (CMP)
    Bean Managed Persistence (BMP)
        Design of Distributed Software                                47
                                                                                     1. Introduction
  Web Centric Architecture
Client                              Webserver              Application Server   Database system

                                                             Web container
   browser                              webserver
   applet
            applet




                                                             EJB container
                                             Servlet
                                             JSP
                                             EJB
Web container services                                 EJB container services
• component life cycle management                      • component life cycle management
• handle communication with                            • transaction service
  webserver HTTP <-> servlet                           • persistence service
• session tracking                                     • security handling
                                                       • resource pooling
            Design of Distributed Software                                                      48
                                                       2. Servlets
   Servlet life cycle
If webcontainer receives request for non-instantiated servlet
1. Load Servlet class
2. Instantiate object of Servlet class
3. Initialize Servlet
        -> call init() method
4. Invoke service()-method to handle request
5. Handle any new requests by invoking service()
6. If idle-time > timeout or request by admin
        Remove servlet from webcontainer
        -> call destroy() method
        (clean up)



       Design of Distributed Software                                49
                                                                                       2. Servlets
    Servlet life cycle
                                                Application Server

                                Request               ServletContext
         webserver
                                     Response       Servlet             Servlet

                                                                                  Servlet
                                                              Servlet

• Single Servlet instance handles all                              Web container
  requests for given Servlet class (exception : SingleThreadModel)
• Servlet invoked per request
• Servlet state does not survive requests
• “long lived” storage :
        - through ServletContext object (e.g. Session persistence)
        - in database (persistent storage)
GenericServlet : protocol neutral Servlet
HttpServlet : has access to HTTP specifics
          Design of Distributed Software                                                             50
                                                                   2. Servlets
  Servlet types

GenericServlet
      abstract public void service(ServletRequest req,ServletResponse res)
                       throws ServletException, IOException
      • method called for each request
      • method not synchronized by default !


HttpServlet
     Inherits from GenericServlet
     Overrides service-method
              - automatically dispatches to HTTP-message related methods
              public void doGet(HttpServetRequest req,HttpServletResponse res)
                      throws ServletException, IOException
              public void doPost(HttpServetRequest req,HttpServletResponse res)
                      throws ServletException, IOException


      Design of Distributed Software                                             51
                                                                               2. Servlets
      A GenericServlet

import java.io.*;
import javax.servlet.*;


public class RandomGenericServlet extends GenericServlet {
  public void service(ServletRequest req,ServletResponse res)
                                       throws ServletException,IOException {
     res.setContentType("text/html");
     PrintWriter out=res.getWriter();
     out.println("<HTML><HEAD><TITLE>RandomGenericServlet Output
                                                           </TITLE></HEAD>");
     out.println("<BODY> Your random number is : "+
                                                 ((int)(Math.random()*10))+"</BODY>");
     out.println("</HTML>");
     out.close();
  }
}                            • Override service()-method
                             • Set MIME-content type BEFORE writing to Response-object


            Design of Distributed Software                                                   52
                                                                                  2. Servlets
    An HttpServlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class RandomHttpServlet extends HttpServlet {
  public void doGet(HttpServletRequest req,HttpServletResponse res)
                                         throws ServletException,IOException {
     res.setContentType("text/html");
     PrintWriter out=res.getWriter();
     out.println("<HTML><HEAD><TITLE>RandomGenericServlet Output
                                         </TITLE></HEAD>");
     out.println("<BODY> Your random number is : "+
                                         ((int)(Math.random()*10))+"</BODY>");
     out.println("</HTML>");
     out.close();
  }
  public void doPost(HttpServletRequest req,HttpServletResponse res)
                                         throws ServletException,IOException {
     doGet(req,res);
  }                                   • No service-method
}                                     • Override doXXX()-methods
                                                 XXX=Get,Post,Put,Trace,Delete,Options
           Design of Distributed Software                                                       53
                                                                                     2. Servlets
       Servlet framework methods
Automatically called methods
        public void init(ServletConfig config)
              • called by container when Servlet is loaded
              • if overriden : first statement should be super.init(config)
              • calls init() method
                              (better to override init() !)
        public void init()
              • called by init(ServletConfig)
              • code non-standard initialization here (e.g. Open database connection)

         public void destroy()
              • called by container when Servlet unloaded or timeout
              • locate clean-up code here (close file handles, database connections, sockets, etc.)
              • DANGER : make this method thread-safe !!!

        public abstract void service(ServletRequest req, ServletResponse res)
             • called when request received
             • overriden in HttpServlet class to dispatch to HTTP-related methods
Convenience method
        public void log(String log) : write (error)message to container specific log file



             Design of Distributed Software                                                        54
                                                                                        2. Servlets
      Servlet environment
                                      ServletContext I
         ServletRequest
                                                                               XML
                                   Servlet        Servlet                      deployment
                                                                               Description
       ServletResponse




                                                               Web container
                                                                               Application I


                                                                               XML
                                   Servlet        Servlet                      deployment
                                                                               Description
                                                                               Application II

                                       ServletContext II
Servlet configuration
          - static info used for deploying the Servlet
          - initialisation parameters
Servlet context
          - object allowing to interact with web application
          - used to track sessions !
Servlet request/response
          - request holds input parameters for Servlet
             Design of Distributed Software                                                           55
                                                                                2. Servlets
     ServletConfig
Servlet config object passes servlet-specific info (NO request specific info)


public ServletConfig getServletConfig()
public String getServletInfo()
           info on author, version, ... (override to supply info)
public String getServletName()
           returns Servlet instance name (as known to container)
public String getInitParameter(String parName)
           ALWAYS type String (Servlet should parse)
public Enumeration getInitParametersNames()
           returns Enumeration of names for all known init parameters

init parameters
          - parameter (name,value)-pairs stored in war-file
          - initialized when servlet is loaded
          - setting init-parameters is server dependent




           Design of Distributed Software                                                     56
                                                                              2. Servlets
     ServletConfig

Intialize database connection
           public void init() {
                     String dbHost=getInitParameter(“host”);
                     int port=Integer.parseInt(getInitParameter(“dbport”));
                     String user=getInitParameter(“user”);
                     String pass=getInitiParameter(“password”);
                     // initialize connection to database
           }

Show all init-parameters
          public String getServletInfo() {
                    String res=“”;
                    Enumeration e=getInitParameterNames();
                    while(e.hasMoreElements())
                              res+=(String)(enum.nextElement());
                    return res;
          }



           Design of Distributed Software                                                   57
                                                                                     2. Servlets
       ServletContext
Servlet context object serves as interface to container
One context per web application
If distributed web application : one context per JVM per web application

public ServletContext getServletContext()
public ServletContext getServletContext(String uri)
          returns context object for uri specified servlet      Same as for config object,
public String getInitParameter(String parName)                  But for CONTEXT wide init
public Enumeration getInitParametersNames()                     Parameters (shared between servlets)
public RequestDispatcher getRequestDispatcher(String path)
          returns RequestDispatcher for given path
public RequestDispatcher getNamedDispatcher(String name)
          returns RequestDispatcher for referred servlet
public Object getAttribute(String name)
          return Object with given name
public Enumeration getAttributeNames()
          return names for all context attributes
public void removeAttribute(String name)
          removes named attribute from context
public void setAttribute(String name,Object obj)
          add attribute obj, name it “name”

             Design of Distributed Software                                                        58
                                                                                       2. Servlets
       ServletRequest
- request holds input parameters for Servlet
- created by container and handed to service()-method
public Object getAttribute(String name)                      Same as for context object,
public Enumeration getAttributeNames()                       But for Request Scope
public void removeAttribute(String name)                     Attributes
public void setAttribute(String name,Object obj)
public String getServerName()
public int getServerPort()
public String getRemoteAddress()
public String getRemoteHoser()
public BufferedReader getReader() // buffered char reader
public ServletInputStream getInputStream() // binary reader
public String getProtocol()
public int getContentLength()
public String getParameter()                               Request encoded parameters
public String[] getParameterValues()                       -request body – POST
public Enumeration getParameterNames()                     -URL encoded - GET
public Map getParameters() // name – value map




              Design of Distributed Software                                                         59
                                                                                    2. Servlets
       HttpServletRequest

public String getHeader(String name)
public Enumeration getHeaders(String name)
public Enumeration getHeaderNames()
public String getMethod()
public Cookie[] getCookies()                                           Session
public HttpSession getSession()                                        management
public HttpSession getSession(boolean create)

                http://somehost:80/directory/servlet/pathinfo?query


                                    public String getPathInfo()

                                      public String getQueryString()




             Design of Distributed Software                                                       60
                                                                            2. Servlets
     HttpServletRequest : headers

User-Agent                   information on client side software
Referer                      URL from which Servlet is accessed
Host                         Internet host and port of requested resource
Accept                       comma-separated list of MIME-types accepted by the client
Accept-Charset               character set accepted by client
Accept-encoding              accepted content-encoding (mainly compression)
                             e.g. “compress”, “deflate”, “gzip”
Accept-Language              preferred language by client software
                             (e.g. “en”, “de”,”en-us”,...)
Authorization                used to authorize user (server specific)
Connection                   options for this connection
                             (“close”, “keep-alive”)
Pragma                       destined for intermediary
                             (e.g. “no-cache” -> no proxy caching)




           Design of Distributed Software                                                 61
                                                                                           2. Servlets
        HttpServletRequest : headers
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HeaderServlet extends HttpServlet {
  public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException {
    res.setContentType("text/html");
    PrintWriter out=res.getWriter();
    out.println("<HTML><HEAD><TITLE>HeaderServlet Output</TITLE></HEAD>");
    Enumeration names=req.getHeaderNames();
    out.println("<H1>Request Headers</H1>");
    while(names.hasMoreElements()) {
       String headerName=(String)names.nextElement();
       String headerValue=req.getHeader(headerName);
       out.println("<B>"+headerName+" : </B>"+headerValue+"<BR>");
    }
    out.println("</HTML>");
    out.close();
  }
  public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException {
    doGet(req,res);
  }
}

               Design of Distributed Software                                                            62
                                                                                 2. Servlets
HttpServletRequest : headers




                                                                                View Source
                        <HTML><HEAD><TITLE>HeaderServlet Output</TITLE></HEAD>
                        <H1>Request Headers</H1>
                        <B>accept : </B>image/gif, image/x-xbitmap, image/jpeg,
                        image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint,
                        application/msword, application/x-shockwave-flash, */*<BR>
                        <B>accept-language : </B>nl-be<BR>
                        <B>accept-encoding : </B>gzip, deflate<BR>
                        <B>user-agent : </B>Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)<BR>
                        <B>host : </B>localhost:8080<BR>
                        <B>connection : </B>Keep-Alive<BR>
                        </HTML>
  Design of Distributed Software                                                              63
                                                                          2. Servlets
       HTML parameter encoding

In FORM-tag

Field type                    Value                       Example

text                          String or null(empty)       name=Kennedy
hidden                        String or null(empty)       sessionID=12234
checkbox                      checked : String            box=on
                               either “on”,”true”,”yes”   box=John
                               OR assigned tag value
                              unchecked : null
radio                         String                      name=John
select option                 String or null              car=Fiat
textarea                      String or null (empty)      text=this is some sample text




              Design of Distributed Software                                            64
                                                                                              2. Servlets
       Retrieving parameters
<html><head><title> Personal ID </title></head>
<body>
<FORM METHOD="GET" ACTION="http://localhost:8080/process/input">
 <P>Enter name <INPUT TYPE="text" NAME="name" SIZE=20></INPUT></P>
 <P>Occupation :<BR>
 <INPUT TYPE="checkbox" NAME="USpres">US president<BR>
 <INPUT TYPE="checkbox" NAME="NMBS">NMBS manager<BR>
 <INPUT TYPE="checkbox" NAME="prime">Belgian Prime Minister<BR>
 </P>
 <P>Sex : <BR>
 <INPUT TYPE="radio" NAME="sex" VALUE="male" CHECKED>male<BR>
 <INPUT TYPE="radio" NAME="sex" VALUE="female">female<BR>
 <P>Select your favourite car : <BR>
 <SELECT NAME="cars">
           <OPTION VALUE="volvo">Volvo
           <OPTION VALUE="saab">Saab
           <OPTION VALUE="fiat">Fiat
           <OPTION VALUE="audi">Audi            • input to be processed on http://localhost:8080/process/input
 </select>                                      • using doGet()-method
 </P>                                           • parameter names : name, USpres, NMBS, prime, ...
 <P>Your comments :<BR>
 <TEXTAREA NAME="comments" ROWS="5" COLS="30">
 </TEXTAREA>
 </P>
 <INPUT TYPE="submit" VALUE="Submit ID card">
</FORM>
</body>       Design of Distributed Software                                                              65
</html>
                                    2. Servlets
Retrieving parameters




 Browser
 output




   Design of Distributed Software                 66
                                                                                          2. Servlets
      Retrieving parameters
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ProcessInput extends HttpServlet {
  public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException {
    res.setContentType("text/html");
    PrintWriter out=res.getWriter();
    out.println("<HTML><HEAD><TITLE>Echo back to confirm.</TITLE></HEAD>");
    out.println("<BODY>");
    out.println("You have entered following data :<BR>");
    out.println("Your name : "+req.getParameter("name")+"<BR>");
    out.print("Your occupations : ");
    if(req.getParameter("USpres")!=null) out.print("US president ");
    if(req.getParameter("NMBS")!=null) out.print("NMBS manager ");
    if(req.getParameter("prime")!=null) out.print("Belgian Prime Minister ");
    out.println("<BR>");
    out.println("Your sex : "+req.getParameter("sex")+"<BR>");
    out.println("Your favourite car : "+req.getParameter("cars")+"<BR>");
    out.println("Your comments : "+req.getParameter("comments")+"<BR>");
    out.println("</BODY>");
    out.println("</HTML>");
    out.close();
  }
}


             Design of Distributed Software                                                             67
                                           2. Servlets
   Retrieving parameters

Browser
output




          Design of Distributed Software                 68
                                                                       2. Servlets
      ServletResponse

Webcontainer
   • retrieves ServletResponse object
   • translates to HTTP and manages connection


public void setContentType(String type)
          • sets MIME-type of response (e.g. “text/html”)
          • MIME type MUST be set before generating output
public void setContentLength(int len)
public ServletOutputStream getServletOutputStream() // binary output
public PrintWriter getWriter() // formatted character output
public Enumeration getInitParameters()




            Design of Distributed Software                                           69
                                                                               2. Servlets
      HttpServletResponse

public void addHeader(String name,String value)
public void setHeader(String name,String value)
public boolean containsHeader()
public void addDateHeader(String name,long date) // ms since January 1, 1970
public void setDateHeader(String name,long date) // ms since January 1, 1970


public sendError(int http_statuscode)
public sendError(int http_statuscode,String message)
                   e.g. sendError(404,”Can not find this file here.”)

public sendRedirect(String url)
                  e.g. sendRedirect(http://newhost/index.html)

public setStatus(int http_statuscode)
                   e.g. setStatus(404)

public void addCookie(Cookie c) Session
                                      management

            Design of Distributed Software                                                   70
                                                                           2. Servlets
     HttpServletResponse : headers

Age                        time elapsed since response generated (control caching)
Allow                      list of supported http methods for requested document
Content-Encoding           type of encoding used for (e.g. compressed) response
Content-Language           natural language used for the response
Content-Length             number of bytes of the document’s body
Content-Type               MIME-type of response
Date                       Current date and time (GMT)
Expires                    date and time (GMT) when content becomes stale
                           (can not be cached any longer)
Last-Modified              date and time (GMT) since last update (used for cache control)
Refresh                    number of seconds before document should be reloaded
Server                     server info
WWW-Authenticate           for authorization, server specific




         Design of Distributed Software                                                  71
                                                                        2. Servlets
Servlet collaboration

Sharing data

Within same application : use ServletContext attributes

With another application/context ON SAME SERVER :
    • use database
    • use external object (on same or different server)
    • use ServletContext of other application

         ServletContext ownContext= getServletContext();
         ServletContext otherContext=ownContext.getContext(“/otherapp/index.html”);
         Object parameter=otherContext.getAttribute(“foreignAttribute”);

Sharing control

Use RequestDispatcher to forward/include to component contents




     Design of Distributed Software                                                   72
                                                                             2. Servlets
  Servlet chaining / forwarding

• make sure all headers are set appropriately before forwarding requests
• through RequestDispatcher-object


  Use getRequestDispatcher()-methods

  forward(ServletRequest request, ServletResponse response)
           -> forward request to other resource, hand off control
           -> response NOT committed to client !

  include(ServletRequest request, ServletResponse response)
           -> include contents to response of this servlet,
              original servlet stays in control


                   // …
                   String destination=“/servlet/NewServlet”;
                   RequestDispatcher dispatcher= req.getRequestDispatcher(destination);
                   dispatcher.forward(req,res);
                   // …

        Design of Distributed Software                                                     73
                                                                                  2. Servlets
   Servlet forwarding : example
                                          Check credentials
                                                                         Process input text

                                            ValidServlet       forward
                                                                           ProcessServlet
                          invalid                              valid



HTML-input form                           Known to webserver              Known to webserver
Fields : name, password, text             as “valid”                      as “process”


                                 Web application “forward” contains :
                                 • HTML-input form “index.html”
                                 • Servlet “valid” instance of class ValidServlet.class
                                 • Servlet “process” instance of class ProcessServlet.class



                                                       forward.war


         Design of Distributed Software                                                         74
                                                                           2. Servlets
      Servlet forwarding : example
                                                              index.html
<html>
<head>
<title> Forward </title>
</head>

<body>
<FORM METHOD="GET" ACTION="http://localhost:8080/forward/valid">
 <P>Enter user name <INPUT TYPE="text" NAME="user" SIZE=20></INPUT></P>
 <P>Password <INPUT TYPE="password" NAME="pass" SIZE=20></INPUT></P>
 <P>Enter text to send to database :<BR>
 <TEXTAREA NAME="text" ROWS="5" COLS="30">
 </TEXTAREA>
 </P>
 <INPUT TYPE="submit" VALUE="Submit Text">
</FORM>
</body>
</html>




             Design of Distributed Software                                              75
                                                                                              2. Servlets
     Servlet forwarding : example
                                                                        ValidServlet.java
public class ValidServlet extends HttpServlet {
  public void doGet(HttpServletRequest req,HttpServletResponse res)throws
                                                                   ServletException,IOException {
    String user=req.getParameter("user");
    String pass=req.getParameter("pass");
    if(user.equals("user")&&pass.equals("secret")) {
           RequestDispatcher dispatcher=req.getRequestDispatcher("process");
           dispatcher.forward(req,res);
    } else {
       res.setContentType("text/html");
       PrintWriter out=res.getWriter();
       out.println("<HTML><HEAD><TITLE>Answer from ValidServlet.</TITLE></HEAD>");
       out.println("<BODY>");
       out.println("You failed to supply valid credentials.<BR>");
       out.println("</BODY>");
       out.println("</HTML>");
       out.close();
    }
  }
  public void doPost(HttpServletRequest req,HttpServletResponse res) throws
                                                                   ServletException,IOException {
    doGet(req,res);
  }
}

             Design of Distributed Software                                                                 76
                                                                             2. Servlets
    Servlet forwarding : example
                                                              ProcessServlet.java
public class ProcessServlet extends HttpServlet {
  public void doGet(HttpServletRequest req,HttpServletResponse res)throws
                                                        ServletException,IOException {
     String text=req.getParameter("text");
     res.setContentType("text/html");
     PrintWriter out=res.getWriter();
     out.println("<HTML><HEAD><TITLE>Answer from ProcessServlet.</TITLE></HEAD>");
     out.println("<BODY>");
     out.println("Following text has been submitted :<BR>"+text);
     out.println("</BODY>");
     out.println("</HTML>");
     out.close();
   }
  public void doPost(HttpServletRequest req,HttpServletResponse res)throws
                                                        ServletException,IOException {
     doGet(req,res);
  }
}




          Design of Distributed Software                                                   77
                                                                              3. JSP
     Java Server Pages
• allows to use convenient syntax for static portions
• JAVA-scriptlets to code dynamic parts
• intuitive interaction with Java Beans components
• jsp-file is compiled in single Servlet

                      Application Server


                             ServletContext
         request                                              Servlet class
                                       Deployed
                                       JSP/Servlet
                                                             JAVA-compiler
         reply               Servlet

                                             Web container   Servlet source


                                               war-file      JSP-compiler


                                                                JSP-file


            Design of Distributed Software                                             78
                                                                                         3. JSP
          A Simple Example
                                           Servlet version
import java.io.*;
import javax.servlet.*;


public class RandomGenericServlet extends GenericServlet {
  public void service(ServletRequest req,ServletResponse res)
                      throws ServletException,IOException {
    res.setContentType("text/html");
    PrintWriter out=res.getWriter();
    out.println("<HTML><HEAD><TITLE>Servlet Output
                      </TITLE></HEAD>");
    out.println("<BODY> Your random number is : "+
                      ((int)(Math.random()*10))+"</BODY>");
    out.println("</HTML>");
    out.close();
  }                                                                              JSP-version
                                       <%@page contentType="text/html"%>
}
                                         <html>
                                         <head><title>JSP output</title></head>
                                         <body>
                                         Your random number is : <%=((int)(Math.random()*10))%>
                                         </body>
                                         </html>

                  Design of Distributed Software                                                  79
                                                                          3. JSP
 Object Scoping
Recap from Servlets :

Application scope
          all JSP-pages and resources sharing same ServletContext
          e.g.
                    String myString=“example variable”;
                    getServletContext.setAttribute(“example”,myString);

Session scope
         all resources in current HttpSession
         e.g.
                   HttpSession session=req.getSession(true);
                   sess.setAttribute(“example”,myString);

Request scope
         this request only
         e.g.
                   req.setAttribute(“example”,myString);

Page scope
        this page only (no servlet equivalent) (default for JSP)

        Design of Distributed Software                                             80
                                                                                  3. JSP
  Syntax
Declarations
application scope declarations
     • variables and methods
     • OUTSIDE servlet service()-method
     • syntax :    <%!         the declarations     %>
request scope declarations
     • variables local to service()-method                  public class TheServlet {
     • comes INSIDE servlet service()-method
     • syntax : same as scriptlets
           <%       the declarations %>                               public void service(…) {
 Scriptlet
   Piece of java-code for service()-method
        syntax :    <%          the java code        %>               }
                                                            }
Escaping
        Literal sequence                 meaning
        <\%                              <%
        %\>                              %>
        \’                               ‘       (for single quote in single quoted attribute)
        \”                               “       (for double quote in double quoted attribute)
        Design of Distributed Software                                                      81
                                                                          3. JSP
 Syntax
Expressions

Dynamically generated output
    • evaluate Java-expression
    • apply toString() if necessary
    • send to JSP output stream (end hence ServletOutputStream)
    • syntax :    <%=         the java expression %>           (no ; !)


Comments

HTML-comments
    • visible in browser (“view source”)
    • embedded scriptlets/expressions in HTML-comments are executed/evaluated
    • syntax : <!--          the comment    -->
Java-comments
    • standard java-comment in scriptlets
    • do not appear in HTML-output
    • syntax : <%            // the comment %> (or multi-line comment syntax)

JSP-comments
    • ignored by the JSP-compiler (do not appear)
    • syntax : <%--        the comment        -->
       Design of Distributed Software                                              82
                                                                                            3. JSP
          Syntax
 Directives

 Messages to the JSP engine
 Syntax : <%@ directive attribute=“value” %>

 page

Attributes                                meaning
contentType                               sets MIME-type of response
                                          <%@ page contentType=“text/html” %>
extends                                   specify superclass of JSP’s associated Servlet
                                          <%@ page extends=“com.SuperServlet” %>
import                                    specify packages to import
                                          <%@ page import=“java.util.*” %>
info                                      sets ServletInfo variable
                                          <%@ page info=“Hello Servlet echoes request” %>
errorPage                                 specify jsp to redirect in case of uncaught exception
                                          <%@ page errorPage=“ErrPage.jsp” %>
isErrorPage                               indicate if this page is error page for other page, true or false
                                          <%@ page isErrorPage=“true” %>
session                                   true or false : participate in session ?
                                          <%@ page session=“false” %>
              Design of Distributed Software                                                          83
                                                                                   3. JSP
 Syntax
include

Include other file (jsp, html, textfile, …, in current jsp)
• static include (at JSP-compile time)
• includes interpreted in “cut and paste” fashion
           <%@ page include=“jspfiles/MyJSP.jsp” %>

taglib            Inclusion of Custom Tag Libraries
                  Extension mechanism for JSPs

Implicit objects      Objects made available to JSP-page

          Name                                    meaning
          application                             ServletContext
          config                                  ServletConfig
          exception                               Exception object (only for error pages)
          page                                    this
          request                                 HttpServletRequest
          response                                HttpServletResponse
          session                                 HttpSession
          Design of Distributed Software                                                    84
                                                                                           3. JSP
      Syntax
Actions

Statement                                       meaning
jsp:include                                     dynamic include of resource
                                                <jsp:include page=“myjsps/included.jsp” flush=“true” />
                                                second attribute MUST be true
jsp:forwa rd                                    forward request to other resource (specified as URL)
                                                <jsp:forward page=“other.jsp” />
                                                must be resource of same application

                       forwarding WITH parameters :
                        <jsp:forward page=“other.jsp” >
                                 <jsp:param name=“parname” value=“parval”/>
                       </jsp:forward>

jsp:plugin                                      include Applet using Java-plugin

                       <jsp:plugin type=”applet” code=“myApplet.class” with=“100” height=“200” >
                                 <jsp:params>
                                           <jsp:param name=“car” value=“Volvo” />
                                 </jsp:params>
                       </jsp:plugin>
               Design of Distributed Software                                                        85
                                                                                    3. JSP
     Syntax
Actions : interaction with JavaBeans

Instantiating a Bean


     <jsp:usebean id=“beanInstanceName” scope=“the scope” beandetails />



     Scope attribute : valid values “page” (default), “request”, “session”, “application”
     beandetails:
               attributes :
                         class              Bean class file (usually required)
                         type               dynamic typing (cast)
                         beanName           class file, can be expression
     If bean already exists with this name and scope, the bean is not re-instantiated
     Bean class MUST have no-arg public constructor !

     <jsp:usebean id=“myBean” scope=“session” class=“MyBean.class” type=“Object.class”/>

     =         Object myBean=(Object) new MyBean();

            Design of Distributed Software                                                   86
                                                                            3. JSP
      Syntax
 Actions : interaction with JavaBeans

Bean properties
<jsp:getProperty name=“beanInstanceName” property=“propertyname”/>
Property value converted to String

<jsp:setProperty name=“beanInstanceName” property=“propertyname” value=“propValue” />
<jsp:setProperty name=“beanInstanceName” property=“propertyname”
                                                   param=“requestParameterName” />

      How to transform requestParameter (always String) to BeanProperty ?

      • if PropertyEditor available : setAsText() used
      • primitives : valueOf(String) used

<jsp:setProperty name=“beanInstanceName” property=“propertyname” />
         -> sets property according to matching request parameter
<jsp:setProperty name=“beanInstanceName” property=“*” />
         -> sets all properties according to request parameters

            Design of Distributed Software                                              87
                                                         3. Application design
     Technologies
Different technologies to execute code




               JSP                             Servlet




        Enterprise                          Database
        Java Beans                          Stored procedures

           Design of Distributed Software                                 88
                                                                    3. Application design
Typical technology role
Presentation              Business Logic       Database system




                                                  JDBC
                JSP : intuitive graphical representation
                Servlet : execute business logic (e.g. data validation)
                Enterprise Java Beans : local storage
                Stored procedure (SQL) : optimize database access


      Design of Distributed Software                                                 89
                                                     4. Java Server Faces
    Java Server Faces (JSF)
 Java-based Web application framework
 Goal: simplify development of user interfaces for Java EE
  applications.
 The state of UI components is saved when the client requests
  a new page and then is restored when the request is returned.
 JSF uses JavaServer Pages (JSP) for its display technology.
 There is a server side event model (e.g. ActionListeners and
  ValueChangedListener).
 After compilation and deployment of the application, the client-
  server interaction takes place the same way as with
  Servlets/JSP.
 http://java.sun.com/javaee/javaserverfaces/
 http://java.sun.com/javaee/5/docs/tutorial/doc/bnaph.html

      Design of Distributed Software                                 90
                                                                5. Apache Struts
    Apache Struts
   Open-source web application framework for developing Java EE web
    applications.
   It uses and extends the Java Servlet API to encourage developers to adopt
    a model-view-controller (MVC) architecture.
   Goal: to separate the model (application logic that interacts with a
    database) from the view (HTML pages presented to the client) and the
    controller (instance that passes information between view and model).
   Struts provides the controller (a servlet known as ActionServlet) and
    facilitates the writing of templates for the view or presentation layer
    (typically in JSP, but XML/XSLT is also supported).
   The web application programmer is responsible for writing the model code,
    and for creating a central configuration file struts-config.xml which binds
    together model, view and controller.
   After compilation and deployment of the application, the client-server
    interaction takes again place the same way as with Servlets/JSP.

   http://struts.apache.org/
   http://struts.apache.org/2.0.11.2/docs/tutorials.html

        Design of Distributed Software                                             91
                                                      6. Invocation of EJBs
    Invocation of EJBs
   Enterprise Java Beans are Java objects, run inside a JEE
    application server.
   The application server is responsible for the life cycle
    management of the objects.
   Enterprise Java Beans run inside the same application server
    can easily obtain a reference of each other and invoke
    methods.
   Remote clients (i.e. run outside the application server, either
    standalone or in another application server) can obtain a
    reference to an Enterprise Java Bean (through a JNDI service,
    as described in the next chapter) and invoke its methods.
   In terms of invocation, there is no distinction between session
    beans or entities.


       Design of Distributed Software                                  92
                                                       7. Ajax
    Ajax
   AJAX = Asynchronous JavaScript and XML
   based on xHTML and CSS, the Document Object Model, XML
    and XSLT, the XMLHttpRequest object for asynchronous
    communication with the back-end server and JavaScript to
    bind everything together.
   JavaScript code can communicate directly with the server,
    through the JavaScript XMLHttpRequest object.
   This object allows to send or retrieve information to or from a
    server over HTTP.
   At the client side, JavaScript takes care of creating the
    XMLHttpRequest object, sending or retrieving information
    through it and processing the results.

   http://www.w3schools.com/ajax/


       Design of Distributed Software                             93

								
To top