Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

93
Design of Distributed Software 2. Distributed 2. Distributed Objects and Remote Objects and Remote Invocation Invocation Chapter 2.5 and 2.6

Transcript of Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Page 1: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software

2. Distributed Objects 2. Distributed Objects and Remote Invocationand Remote Invocation

Chapter 2.5 and 2.6

Page 2: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 2

Distributed Software TechnologiesDistributed 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

Page 3: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 3

Schema ODSSchema ODSODS - 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

Page 4: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software

2.5 CORBA : Common Object Request Broker Architecture

Page 5: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 5

2.5 Outline2.5 OutlineIntroduction + Motivation

Corba Implemen-tations

Advanced Architecture

Portable Object Adapter

Corba Framework

Basic Architecture Corba Object Model Corba Object Refs

Basic Corba Example

Extended Corba Example

Page 6: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 6

Situating CORBASituating 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

Page 7: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 7

CORBA: Basic IdeaCORBA: 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.

Page 8: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 8

CORBA ORBCORBA ORB

OMG introduced ORB ORB = Object Request Broker Software component which helps a client to invoke a

method on an object

Timeline :

Page 9: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 9

CORBA framework componentsCORBA 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

Page 10: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 10

RMI : architectureRMI : architecture

Remote Ref. Mod.

communicationcommunication

client server

a b

Remote Ref. Mod.

proxy_bdispatcher skeleton

• proxy• 1 proxy per remote object• local representative of remote object• implements all methods of remote interface• handles (un)marshalling

• dispatcher• typically 1 per class• identify message to invoke in skeleton

• skeleton• typically 1 per class• (un)marshalling• invokes method on remote object• sends reply

Remote Ref Module : •remote object reference table• table of local proxies

Page 11: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 11

CORBA : architectureCORBA : architecture

ORB Core ORB Core

client server

ab

proxy_bdispatcher

skeleton

• ORB Core• cfr Communication Module• Provides interface:

• start/stop ORB• convert between remote objects and strings• provide argument lists for requests using dynamic invocation

• Object Adapter• Remote Ref + Dispatcher• creates remote object references for CORBA objects • dispatches each invocation to the appropriate servant• activates objects• Portable Object Adapters = POAs

Object Adapter

Page 12: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 12

CORBA architecture (2)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

Page 13: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 13

CORBA RMI : Object ModelCORBA RMI : Object Model CORBA’s object model :

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

A B C D E

Page 14: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 14

CORBA ObjectsCORBA Objects

data

Method 1Method 2Method 3

A

Client

CORBA Object

Page 15: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 15

CORBA IDL interface exampleCORBA IDL interface example#ifndef __ECHO_IDL__

#define __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();

};

#endif

echo.idl :

Page 16: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 16

CORBA RMI : IDLCORBA 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

Page 17: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 17

CORBA RMI : pseudo objectsCORBA 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

Page 18: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 18

CORBA client and server exampleCORBA client and server example

IDL compiler :

*.idl files

IDL compiler(idlj)

Java Interface files

Server Skeletons

Proxy Classes or Client Stubs

Java classes for structs

Helper and Holder classes

echo.idl

echo.java

_echoImplBase.java

_echoStub.java

echoHelper.java$ idlj -fall –oldImplBase echo.idl

Page 19: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 19

Java interface fileJava 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

Page 20: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 20

Servant Class ImplementationServant Class Implementationimport 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; }}

Page 21: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 21

Servant ClassesServant 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)

Page 22: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 22

Server Class ImplementationServer Class Implementationimport 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

Page 23: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 23

CORBA serverCORBA 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

Page 24: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 24

Client Implementation 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); } //main} // class

Page 25: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 25

Client ProgramClient 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

Page 26: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 26

Running the server and clientRunning 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!“.

Page 27: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 27

Chapter OutlineChapter OutlineIntroduction + Motivation

Corba Implemen-tations

Advanced Architecture

Portable Object Adapter

Corba Framework

Basic Architecture Corba Object Model Corba Object Refs

Basic Corba Example

Extended Corba Example

Page 28: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 28

CORBA implementationsCORBA 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

Page 29: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 29

Portable Object AdapterPortable Object Adapter

ORB Core

server

bdispatcher

skeleton

Object Adapter

object adapter : connects a request using an object

reference with the proper code to service that request

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.

Page 30: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 30

Example: Echo Servant with POAExample: Echo Servant with POAimport 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; }}

Page 31: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 31

Example: Echo Server with POAExample: Echo Server with POAimport 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

Page 32: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 32

Server Implementation with POAServer 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 instanceechoServant 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 referenceecho echoRef = echoHelper.narrow(ref);

6. Wait for incoming requests from clientsorb.run()

Page 33: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 33

Interface Definition LanguageInterface 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

Page 34: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 34

Interface Definition Language (2)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

Page 35: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 35

More advanced IDL example:More advanced IDL example:

struct Rectangle{long width; long height;long x;long y;

} ;

struct GraphicalObject {string type; Rectangle enclosing; boolean isFilled;

};

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 referenceslong getVersion() ;

};

Whiteboard.idl

Page 36: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 36

IDL moduleIDL 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 {...};

};

Page 37: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software

2.6 Invocations in JEE Architecture

1. Introduction2. Servlets3. Java Server Pages4. Java Server Faces (JSF)5. Apache Struts6. Invocation of Enterprise Java Beans (EJB)7. Ajax

Page 38: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 38

Web centric architecturesWeb centric architectures

webclientwebserver

HTTP request

Thin client :• web browser• plug-ins

HTTP response

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

1. Introduction

Page 39: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 39

Protocol messages : HTTPProtocol messages : HTTP

Request Response• GET (data encoded in URL)• POST (data encoded in message)• header

• requested content (URL)• HTTP version• response types accepted (MIME, language)• client browser• connection type• POST

• content of request• content length

• REPLY• header

• status (success/failure)• response data + MIME type(Multipurpose Internet Mail Extensions)

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

Application level message formats and behavior

1. Introduction

Page 40: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 40

Addressing resources : URLAddressing 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

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

elections!

1. Introduction

Page 41: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 41

Standard interactionStandard interaction

webclientwebserver

HTTP GET

Typical interactions1. Connect : client opens connection with server2. Request : client sends message to identify resource/service3. Response : server sends message to respond to request4. Disconnect : close client-server connection

HTTP REPLY

Retrieving a (HTML) document

1. Introduction

Page 42: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 42

Dynamic content : CGIDynamic content : CGI• Common Gateway Interface• URL

• specifies (small) program• gives input through URL-parameters• program generates html-output (or output for plug in)

webclientwebserver

HTTP POST

HTTP REPLY

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

INVOKE

1. Introduction

Page 43: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 43

Dynamic content : HTML for CGIDynamic content : HTML for CGIHTML <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

1. Introduction

Page 44: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 44

Servlets and JSPServlets 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

webclientwebserver

HTTP POST

HTTP REPLY

Servlet Container

INVOKE

webclient

1. Introduction

Page 45: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 45

Servlets and JSPServlets 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

active

passive

passive

JSP compiler

Servlet class

HTMLcode

Actually : JSP = Servlet

1. Introduction

Page 46: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 46

EJBEJB• Server side component technology to code application logic

• model business logic• model business objects (“database record”)

webclient

webserver

Servlet Engine

Business tierMiddle TierWeb tier

Persistent Storage tierEntreprise Systems Tier

Ap

pli

cati

on

lo

gic

Applicationclient

Client tier

1. Introduction

Page 47: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 47

EJBEJB

• Session beans

• Entity 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

• 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)

1. Introduction

Page 48: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 48

Web Centric ArchitectureWeb Centric Architecture

browser webserver

Application Serverap

ple

t

app

let

Database system

Web container

EJB container

WebserverClient

Servlet

JSP

EJBWeb container services• component life cycle management• handle communication with webserver HTTP <-> servlet• session tracking

EJB container services• component life cycle management• transaction service• persistence service• security handling• resource pooling

1. Introduction

Page 49: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 49

Servlet life cycleServlet life cycle

If webcontainer receives request for non-instantiated servlet1. Load Servlet class2. Instantiate object of Servlet class3. Initialize Servlet

-> call init() method4. Invoke service()-method to handle request5. 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)

2. Servlets

Page 50: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 50

Servlet life cycleServlet life cycle2. Servlets

Application Server

Web container

Servlet

ServletServlet

Servlet

ServletContextRequest

Response

• Single Servlet instance handles all 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 ServletHttpServlet : has access to HTTP specifics

webserver

Page 51: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 51

Servlet typesServlet types2. Servlets

GenericServlet

HttpServlet

abstract public void service(ServletRequest req,ServletResponse res) throws ServletException, IOException

• method called for each request• method not synchronized by default !

Inherits from GenericServletOverrides service-method

- automatically dispatches to HTTP-message related methodspublic void doGet(HttpServetRequest req,HttpServletResponse res)

throws ServletException, IOExceptionpublic void doPost(HttpServetRequest req,HttpServletResponse res)

throws ServletException, IOException

Page 52: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 52

A GenericServletA GenericServlet2. Servlets

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

Page 53: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 53

An HttpServletAn HttpServlet2. Servlets

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

Page 54: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 54

Servlet framework methodsServlet framework methods2. Servlets

Automatically called methodspublic 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 methodpublic void log(String log) : write (error)message to container specific log file

Page 55: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 55

Servlet environmentServlet environment2. Servlets

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

Servlet Servlet

Web

co

nta

iner

XMLdeployment DescriptionApplication I

ServletRequest

ServletResponse

ServletContext I

Servlet Servlet

XMLdeployment DescriptionApplication II

ServletContext II

Page 56: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 56

ServletConfigServletConfig2. Servlets

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

Servlet config object passes servlet-specific info (NO request specific info)

Page 57: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 57

ServletConfigServletConfig2. Servlets

Intialize database connectionpublic 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-parameterspublic String getServletInfo() {

String res=“”;Enumeration e=getInitParameterNames();while(e.hasMoreElements())

res+=(String)(enum.nextElement());return res;

}

Page 58: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 58

ServletContextServletContext2. Servlets

public ServletContext getServletContext()public ServletContext getServletContext(String uri)

returns context object for uri specified servletpublic String getInitParameter(String parName)public Enumeration getInitParametersNames()public RequestDispatcher getRequestDispatcher(String path)

returns RequestDispatcher for given pathpublic RequestDispatcher getNamedDispatcher(String name)

returns RequestDispatcher for referred servletpublic Object getAttribute(String name)

return Object with given namepublic Enumeration getAttributeNames()

return names for all context attributespublic void removeAttribute(String name)

removes named attribute from contextpublic void setAttribute(String name,Object obj)

add attribute obj, name it “name”

Servlet context object serves as interface to containerOne context per web applicationIf distributed web application : one context per JVM per web application

Same as for config object,But for CONTEXT wide initParameters (shared between servlets)

Page 59: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 59

ServletRequestServletRequest2. Servlets

- request holds input parameters for Servlet - created by container and handed to service()-methodpublic Object getAttribute(String name)public Enumeration getAttributeNames()public void removeAttribute(String name)public void setAttribute(String name,Object obj)public String getServerName()public int getServerPort()public String getRemoteAddress()public String getRemoteHoser()public BufferedReader getReader() // buffered char readerpublic ServletInputStream getInputStream() // binary readerpublic String getProtocol()public int getContentLength()public String getParameter()public String[] getParameterValues()public Enumeration getParameterNames()public Map getParameters() // name – value map

Same as for context object,But for Request ScopeAttributes

Request encoded parameters-request body – POST-URL encoded - GET

Page 60: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 60

HttpServletRequestHttpServletRequest2. Servlets

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

Sessionmanagement

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

public String getPathInfo()

public String getQueryString()

Page 61: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 61

HttpServletRequest : headersHttpServletRequest : headers2. Servlets

User-Agent information on client side softwareReferer URL from which Servlet is accessedHost Internet host and port of requested resourceAccept comma-separated list of MIME-types accepted by the clientAccept-Charset character set accepted by clientAccept-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)

Page 62: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 62

HttpServletRequest : headersHttpServletRequest : headers2. Servlets

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); }}

Page 63: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 63

HttpServletRequest : headersHttpServletRequest : headers2. Servlets

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

View Source

Page 64: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 64

HTML parameter encodingHTML parameter encoding2. Servlets

In FORM-tag

Field type Value Example

text String or null(empty) name=Kennedyhidden String or null(empty) sessionID=12234checkbox checked : String box=on

either “on”,”true”,”yes” box=John OR assigned tag valueunchecked : null

radio String name=Johnselect option String or null car=Fiattextarea String or null (empty) text=this is some sample text

Page 65: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 65

Retrieving parametersRetrieving parameters2. Servlets

<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

</select> </P> <P>Your comments :<BR> <TEXTAREA NAME="comments" ROWS="5" COLS="30"> </TEXTAREA> </P> <INPUT TYPE="submit" VALUE="Submit ID card"> </FORM></body></html>

• input to be processed on http://localhost:8080/process/input• using doGet()-method• parameter names : name, USpres, NMBS, prime, ...

Page 66: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 66

Retrieving parametersRetrieving parameters2. Servlets

Browseroutput

Page 67: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 67

Retrieving parametersRetrieving parameters2. Servlets

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(); }}

Page 68: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 68

Retrieving parametersRetrieving parameters2. Servlets

Browseroutput

Page 69: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 69

ServletResponseServletResponse2. Servlets

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 outputpublic PrintWriter getWriter() // formatted character outputpublic Enumeration getInitParameters()

Page 70: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 70

HttpServletResponseHttpServletResponse2. Servlets

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, 1970public 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) Sessionmanagement

Page 71: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 71

HttpServletResponse : headersHttpServletResponse : headers2. Servlets

Age time elapsed since response generated (control caching)Allow list of supported http methods for requested documentContent-Encoding type of encoding used for (e.g. compressed) responseContent-Language natural language used for the responseContent-Length number of bytes of the document’s bodyContent-Type MIME-type of responseDate 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

Page 72: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 72

Servlet collaborationServlet collaboration2. Servlets

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

Page 73: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 73

Servlet chaining / forwardingServlet chaining / forwarding2. Servlets

• 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);// …

Page 74: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 74

Servlet forwarding : exampleServlet forwarding : example2. Servlets

HTML-input formFields : name, password, text

ValidServlet

Check credentials

invalidProcessServlet

Process input text

valid

forward

Known to webserveras “valid”

Known to webserveras “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

Page 75: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 75

Servlet forwarding : exampleServlet forwarding : example2. Servlets

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

index.html

Page 76: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 76

Servlet forwarding : exampleServlet forwarding : example2. Servlets

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); }}

ValidServlet.java

Page 77: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 77

Servlet forwarding : exampleServlet forwarding : example2. Servlets

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); }}

ProcessServlet.java

Page 78: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 78

Java Server PagesJava Server Pages3. JSP

• 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

Web container

DeployedJSP/Servlet

Servlet

ServletContext

JSP-compiler

JSP-file

Servlet source

JAVA-compiler

war-file

Servlet class request

reply

Page 79: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 79

A Simple ExampleA Simple Example3. JSP

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(); }}

Servlet version

<%@page contentType="text/html"%><html><head><title>JSP output</title></head><body>Your random number is : <%=((int)(Math.random()*10))%></body></html>

JSP-version

Page 80: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 80

Object ScopingObject Scoping3. JSP

Recap from Servlets :

Application scopeall JSP-pages and resources sharing same ServletContexte.g.

String myString=“example variable”;getServletContext.setAttribute(“example”,myString);

Session scopeall resources in current HttpSessione.g.

HttpSession session=req.getSession(true);sess.setAttribute(“example”,myString);

Request scopethis request onlye.g.

req.setAttribute(“example”,myString);

Page scopethis page only (no servlet equivalent) (default for JSP)

Page 81: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 81

SyntaxSyntax3. JSP

application scope declarations• variables and methods• OUTSIDE servlet service()-method• syntax : <%! the declarations %>

request scope declarations• variables local to service()-method• comes INSIDE servlet service()-method• syntax : same as scriptlets

<% the declarations %>

Declarations

public class TheServlet {

public void service(…) {

}}

Escaping

Literal sequence meaning<\% <%%\> %>\’ ‘ (for single quote in single quoted attribute)\” “ (for double quote in double quoted attribute)

Scriptlet

Piece of java-code for service()-method syntax : <% the java code %>

Page 82: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 82

SyntaxSyntax3. JSP

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

Expressions

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

Page 83: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 83

SyntaxSyntax3. JSP

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

Directives

page

Attributes meaningcontentType 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” %>

Page 84: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 84

SyntaxSyntax3. JSP

Include other file (jsp, html, textfile, …, in current jsp)• static include (at JSP-compile time)• includes interpreted in “cut and paste” fashion

include

Name meaningapplication ServletContextconfig ServletConfigexception Exception object (only for error pages)page thisrequest HttpServletRequestresponse HttpServletResponsesession HttpSession

<%@ page include=“jspfiles/MyJSP.jsp” %>

taglib Inclusion of Custom Tag LibrariesExtension mechanism for JSPs

Implicit objects Objects made available to JSP-page

Page 85: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 85

SyntaxSyntax3. JSP

Actions

Statement meaningjsp:include dynamic include of resource

<jsp:include page=“myjsps/included.jsp” flush=“true” />second attribute MUST be true

jsp:forward 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>

Page 86: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 86

SyntaxSyntax3. JSP

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-instantiatedBean class MUST have no-arg public constructor !

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

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

Page 87: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 87

SyntaxSyntax3. JSP

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

Page 88: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 88

TechnologiesTechnologies3. Application design

Different technologies to execute code

JSP Servlet

EnterpriseJava Beans

DatabaseStored procedures

Page 89: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 89

Typical technology roleTypical technology role3. Application design

Business Logic Database systemPresentation

Servlet : execute business logic (e.g. data validation)

JSP : intuitive graphical representation

Enterprise Java Beans : local storage

Stored procedure (SQL) : optimize database accessJD

BC

Page 90: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 90

Java Server Faces (JSF)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

4. Java Server Faces

Page 91: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 91

Apache StrutsApache 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

5. Apache Struts

Page 92: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 92

Invocation of EJBsInvocation 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.

6. Invocation of EJBs

Page 93: Design of Distributed Software 2. Distributed Objects and Remote Invocation Chapter 2.5 and 2.6.

Design of Distributed Software 93

AjaxAjax 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/

7. Ajax