Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A...

110
Li Tak Sing Lectures 7-8-9 COMPS311F 1

Transcript of Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A...

Page 1: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Li Tak SingLectures 7-8-9

COMPS311F

1

Page 2: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Remote Method Invocation(RMI)For distributed computing.A Java object on one system can invoke a

method in an object on another system on the network.

It is build on top of sockets. Users there do not have to handle the sockets anymore. Communication between different computers can be done by invoking methods on a remote computers.

2

Page 3: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

How Does RMI work?Normal objects are called local objects.Objects that can be accessibled by RMI are

called remote objects. For an object to be accessible remotely,

there must be an interface defined in both server and client. The client would only use the interface to access the methods.

The interface must be extended from java.rmi.Remote.

3

Page 4: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Key components of RMI■ Server object interface: A subinterface

of java.rmi.Remote that defines the methods for the server object.

■ Server class: A class that implements the remote object interface.

■ Server object: An instance of the server class.

■ RMI registry: A utility that registers remote objects and provides naming services for locating objects.

4

Page 5: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Key components of RMI■ Client program: A program that invokes

the methods in the remote server object.■ Server stub: An object that resides on

the client host and serves as a surrogate for the remote server object.

■ Server skeleton: An object that resides on the server host and communicates with the stub and the actual server object.

5

Page 6: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Operations of RMI

6

Page 7: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Operations of RMI1. A server object is registered with the RMI

registry.2. A client looks through the RMI registry for

the remote object.3. Once the remote object is located, its stub

is returned in the client.4. The remote object can be used in the

same way as a local object. Communication between the client and the server is handled through the stub and the skeleton.

7

Page 8: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Passing Parameters■ Primitive data types, such as char, int,

double, or boolean, are passed by value like a local call.

■ Local object types, such as java.lang.String, are also passed by value, but this is completely different from passing an object parameter in a local call. In a local call, an object parameter’s reference is passed, which corresponds to the memory address of the object. In a remote call, there is no way to pass the object reference, because the address on one machine is meaningless to a different JVM. Any object can be used as a parameter in a remote call as long as it is serializable. The stub serializes the object parameter and sends it in a stream across the network. The skeleton deserializes the stream into an object.

8

Page 9: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Passing Parameters■ Remote object types are passed differently

from local objects. When a client invokes a remote method with a parameter of a remote object type, the stub of the remote object is passed. The server receives the stub and manipulates the parameter through it.

9

Page 10: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

RMI Registryjava.rmi.registry.LocateRegistry has the

following static methods:public Registry getRegistry(): get the local

registry at default port of 1099.public Registry getRegistry(int port): get the

local registry at the specified port.public getRegistry(String host): get the

remote registry at default port of 1099 on a remote computer.

public getRegistry(String host, int port): get the remote registry at the specified port on a remote computer.

10

Page 11: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Methods of java.rmi.registry.Registryvoid rebind(String name, Remote obj): bind

the specified name to the remote object.void unbind(String name): unbind the

name.Remote lookup(String name): return a

reference of a remote object in the registry.

11

Page 12: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Developing RMI Applications1. Define a server object interface that

serves as the contract between the server and its clients, as shown in the following outline:

public interface ServerInterface extends Remote{public void service1(...) throws RemoteException;

// Other methods}A server object interface must extend the

java.rmi.Remote interface.12

Page 13: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Developing RMI Applications2. Define a class that implements the server

object interface, as shown in the following outline:

public class ServerInterfaceImpl extends UnicastRemoteObject implements ServerInterface {

public void service1(...) throws RemoteException {

// Implement it}// Implement other methods

}13

Page 14: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Developing RMI Applications3. Create a server object from the server

implementation class and register it with an RMI registry:

ServerInterface server = new ServerInterfaceImpl(...);

Registry registry = LocateRegistry.getRegistry();

registry.rebind("RemoteObjectName", obj);

Before running this program, start the RMI registry by running the command rmiregistry at a location where you can find the classes for the server. This can be done by setting appropriate class path or run the command at a suitable location.

14

Page 15: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Developing RMI Applications4. Develop a client that locates a remote

object and invokes its methods, as shown in the following outline:

Registry registry = LocateRegistry.getRegistry(host);

ServerInterface server = (ServerInterfaceImpl)

registry.lookup("RemoteObjectName");server.service1(...);

15

Page 16: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

A simple RMI server that adds two integers.You can download the code at:http://plbpc001.ouhk.edu.hk/~mt311f/

examples/mt3112010/src/rmi.zipThe server has just one method:public int sum(int i,int j)The method would return the sum of i and

j.

16

Page 17: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

RMIAddServerpublic interface RMIAddServer extends

Remote { public int sum(int i, int j) throws RemoteException;

//this method will return the sum of the two integers.

}

17

Page 18: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

RMIAddServerImppublic class RMIAddServerImp extends

UnicastRemoteObject implements RMIAddServer { public RMIAddServerImp() throws

RemoteException { }

public int sum(int i, int j) throws RemoteException {

return i+j; }

18

Page 19: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

RMIAddServerImp public static void main(String st[]) throws

RemoteException { RMIAddServerImp obj=new

RMIAddServerImp();Registry registry=LocateRegistry.getRegistry();

registry.rebind("add", obj); }

}

19

Page 20: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

ADDClientpublic class AddClient { public static void main(String st[]) throws

RemoteException, NotBoundException {Registry

registry=LocateRegistry.getRegistry("localhost");

RMIAddServer server=(RMIAddServer)registry.lookup("add");

System.out.println("The sum of 3 and 4 is "+server.sum(3, 4));

}}

20

Page 21: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Start the serverexecute rmiregistry at a place where

RMIAddServerImp.class can be found. Note that if we have use a package for RMIAddServerImp, then we should run rmiregistry at the parent directory of the package.

21

Page 22: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

RMI vs. Socket-Level ProgrammingRMI enables you to program at a higher

level of abstraction. You do not need to open, close a socket.

RMI server is already multithreaded. So you do not have to worry about multithreading.

22

Page 23: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

RMI callbacksIn previous example, only the client can

initiate a communication with the server. The server can only response to a server's request.

For example, if we want to use RMI to write a chat server, when a client send in a message, we need to send it to all connecting clients. In this case, we need the server to be able to initiate the communication with the clients.

In order for the server to initiate a request, the client should also be a Remote object. The server should have a copy of the stub. This can be done by invoking a remote method by the client which passes itself as a parameter to the server.

23

Page 24: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Passing the client to the serverThe first step is to create a client interface:

public interface Client extends Remote { public void callBack(...) throws RemoteException; }

The server should have a method which allows the client to pass itself as the parameter:public interface Server extends Remote { public void connect(Client client) throws

RemoteException;.......

}24

Page 25: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Implementation of the clientThe implementation of the client should

consists of a statement that invoke the connect method of the server that passes itself to the server:....server.connect(this); // A statement in the client....

25

Page 26: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Implementation of the serverThe server should use an attribute to store

the connected client:public class ServerImp implements Server,

Serializable {private client;public void connect(Client c) throws RemoteException {

client=c;}

....//whenever there is a need to contact the client, we can:client.callBack(..);

....}

26

Page 27: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

A Chat server using RMIYou can download the program at

http://plbpc001.ouhk.edu.hk/~mt311f/examples/mt3112010/src/r.zip

The server is stored in the package RMIChatIn the above file, there is another server in

the package RMIChat2 which we will talk about later.

The program has four files:ChatServer: interface for the chat serverChatServerImp: implementation of the chat

serverChatClient: interface for the chat clientChatClientImp: implementation of the chat

client

27

Page 28: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

ChatServerpublic interface ChatServer extends

java.rmi.Remote { public void send(String st) throws

java.rmi.RemoteException; //the client uses it to send a

//message to the server public void connect(ChatClient c) throws

java.rmi.RemoteException; //the client sends itself to the //server

public void disconnect(ChatClient c) throws java.rmi.RemoteException; //the client disconnect from the //server

}

28

Page 29: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

ChatServerImpIt contains a

JFrame and a JTextArea for the displaying all messages from the clients.

The bottom line displays all connected clients.

29

Page 30: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Declaration of ChatServerImppublic class ChatServerImp extends

UnicastRemoteObject implements ChatServer{

.....}

30

Page 31: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Some Attributes of ChatServerImpVector<ChatClient> clients; //this stores all

connected clients

31

Page 32: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Some Methods of ChatServerImppublic void send(String st) throws

RemoteException { Vector<ChatClient> problem = new

Vector<ChatClient>(); textarea.append(st+"\n"); synchronized (clients) { for (ChatClient c : clients) { try { c.toClient(st); } catch (Exception e) { problem.add(c); }

32

Page 33: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Some Methods of ChatServerImp } for (ChatClient c : problem) { clients.remove(c); } displayClients(); } }

33

Page 34: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Some Methods of ChatServerImppublic void connect(ChatClient c) throws

RemoteException { clients.add(c); displayClients(); }

34

Page 35: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Some Methods of ChatServerImp public void disconnect(ChatClient c) throws

RemoteException { clients.remove(c); displayClients(); }

35

Page 36: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

The main method of ChatServerImp public static void main(String st[]) throws

RemoteException { ChatServer s = new ChatServerImp(); java.rmi.registry.Registry r =

java.rmi.registry.LocateRegistry.getRegistry();

r.rebind("chat", s); }

36

Page 37: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

ChatClientpublic interface ChatClient extends

java.rmi.Remote { public void toClient(String st) throws

java.rmi.RemoteException; //this is the callback for the //server to send a string to the client

public String name() throws java.rmi.RemoteException; //this is another callback for the server to get the name of //the client.

}37

Page 38: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

ChatClientImpThe bottom

textfield is for the user to type in the name.

The connect bottom is used to connect to the chat server.

Once the connection is made, the button becomes the disconnection button.

38

Page 39: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

ChatClientImpThere is a textfield at the top to allow the

user to type a message.When the user presses the send button, the

message would be sent to the server.The message broadcasted from the server

would be displayed on the middle textarea.

39

Page 40: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Declaration of ChatClientImppublic class ChatClientImp extends

UnicastRemoteObject implements ChatClient {

...

40

Page 41: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Some Attributes of ChatClientImpJTextField name; //the textfield at the

bottom of the //window that allows the user to type in the name

JTextArea textarea; //the textarea for the display of //messages broadcasted from the server.

ChatServer server; //the chat server

41

Page 42: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

The action listener of the send button public void actionPerformed(ActionEvent e)

{ try { server.send(name.getText() + ":"

+ textfield.getText()); textfield.setText(""); } catch (RemoteException ex) { } }

42

Page 43: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

The action listener of the connect button public void actionPerformed(ActionEvent e)

{ try { if

(connect.getText().equals("connect")) { Registry registry =

java.rmi.registry.LocateRegistry.getRegistry("localhost");

server = (ChatServer) registry.lookup("chat");

server.connect(ChatClientImp.this);

...

43

Page 44: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

The action listener of the connect button } else { connect.setText("connect");server.disconnect(ChatClientImp.this); }

} catch (NotBoundException ex) { }

44

Page 45: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Some methods of ChatClientImp public String name() throws

RemoteException { return name.getText(); }

public void toClient(String st) throws java.rmi.RemoteException {

textarea.append(st + "\n"); }

45

Page 46: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

The main method of ChatClientImp public static void main(String st[]) throws

RemoteException { new ChatClientImp(); }

Note that we do not need to register the client with any RMI registries. The client would be sent to the server via a method call. So the server would not need to get the client from an RMI registry.

46

Page 47: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Some features of this RMI serverThere is no need to handle multithreading

in the RMI version of the server. Multithreading is handled by the internal mechanism of RMI.

Although we do not create threads, we still need to make the server thread safe as RMI is multithreaded. Therefore, we use the synchronized keyword whenever needed.

47

Page 48: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Problems of the RMI ChatServerAlthough we have a button for the user to

disconnect from the server, it has problem for the server to keep track of clients that have quit execution without informing the server.

In the socket version of the ChatServer, when a client quit execution, a network exception would be thrown at the server side so that the server would know that the client has quit. This is not the case for RMI. The server would not know that a client has quit execution.

48

Page 49: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

The java.rmi.server.Unreferenced interfaceThis interface has one method:

public void unreferenced() throws RemoteException

After a remote object has implemented this interface, then the unreferenced method will be invoked when it is not referenced anywhere.

49

Page 50: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

The java.rmi.server.Unreferenced interfaceThere are several ways that an external

reference to a remote object disappear:The client quits execution.The reference to the object is set to null. For

example:ChatServer server=registry.lookup("chat");

.....server=null; //the remote object is not referenced by server

The variable that references the object is garbage collected.

50

Page 51: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

How to know that a client has quit?For every client that is connected to the

server, we pass to it a newly created object that has implemented the Unreferenced interface. Then, when the client has quit, the object is not reference anywhere as we only pass the object to one client. In this way, the corresponding unreferenced method would be invoked.

51

Page 52: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

But there is a delay before unreferenced is calledNote that the unreferenced method would

only be invoked for a delay of 10 minutes after all referencing clients have quit.

52

Page 53: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Modified Chat server You can find the server in the same file for

the original server. But this time, the server is in the RMIChat2 package.

A new Contact interface is needed for this purpose:public interface Contact extends

java.rmi.Remote {

}The interface has no method. It only use is

to have the object implementing this also implements the Unreferenced interface.

53

Page 54: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Implementation of Contact public class ContactImp extends

UnicastRemoteObject implements Contact, Unreferenced {

private ChatClient client; public ContactImp(ChatClient c) throws

RemoteException { client = c; } public void unreferenced() { clients.remove(client); displayClients(); } }54

Page 55: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Changes to ChatServerImpThe connect method is changed as following: public Contact connect(ChatClient c) throws

RemoteException { clients.add(c); displayClients(); return new ContactImp(c); }

55

Page 56: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Changes to ChatClientThe following attribute is added:

private Contact contact;

The code to connect to the server is changed as following: Registry registry =

java.rmi.registry.LocateRegistry.getRegistry("localhost");

server = (ChatServer) registry.lookup("chat2");

contact=server.connect(ChatClientImp.this);

.......56

Page 57: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Database programmingJDBC (Java Database Connectivity)

Java version of ODBC (Open Database Connectivity)

ODBC provides a standard software interface for accessing database management systems.

Before ODBC, if an application needs to connect to a database, it has to use tailar made APIs for that particular database. Therefore, the program has to be changed if the database is changed, say from Oracle to Access.

ODBC separates the application from the underlying database. The programmer would use the APIs of ODBC. Then ODBC would connact the underlying database.

57

Page 58: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

ODBCWhen the programmer wants to change

database, he/she need to install the corresponding ODBC driver for the database. Then, the application program does not have to be changed.

58

Page 59: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

JDBCSimilarly, JDBC provides a standard set of

APIs to access the underlying database. So when the programmer wants to change the database, there is no need to change the program, but to install the correct JDBC driver for the database.

Of course, since the JDBC and ODBC are still based on the SQL, and difference databases have slight differences in SQL, it is still possible that the programmer may need to change the SQL statements when using the standard JDBC APIs.

59

Page 60: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Using JDBCStep 1 -Loading JDBC driver

The driver translates the vendor-independent JDBC API calls to SQL statements for the database system you are using.

The driver is usually stored as a .jar file. For example, the MySQL driver is called mysql-connector-java-xxx.jar where xxx is the version number. This .jar file must be placed somewhere so that your application can find it. For example, place it in the class path.

To load the driver, execute the statement:class.forName("com.mysql.jdbc.Driver");This only load the mysql driver. For other database,

you need to find out the name of the class. One way to do this is to use an application like winzip, to open the .jar file to see that name.

60

Page 61: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Using JDBCStep 2 - Establishing a connection

In your Java program, you will call the DriverManager to get a database connection.

Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1/jdatabase","user","password");

The getConnection method has three parameters, the first one specifies the URL of the database. The example shows that we want to connect to the mysql database in localhost. The name of the database is called jdatabase. The user name is "user" and the password is "password".

61

Page 62: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Using JDBCStep 2 (cont.)

Of course, in order for the statement to work, the database must be up and running.

Note that this connection will be used through out the application.

Step 3 Creating a statementNow we create a statement using the

Connection object.Statement statement =

connection.createStatement();

62

Page 63: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Using JDBCStep 4 - executing a statement

ResultSet resultSet=statement.executeQuery("select firstName, lastName from

Student where lastname='Wong'");This is for query. For update operations, we

can use the executeUpdate method:statement.executeUpdate("insert into

Student values('Chan Tai Man')");

63

Page 64: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Using JDBCProcessing the result

The ResultSet object returned allows us to retrieve the result row by row. The following loop prints the first and last columns returned by the select statement with a space inserted in between.

while (resultSet.next()) {

System.out.println(resultSet.getString(1)+" "+resultSet.getString(2));}

The next() method of ResultSet will move the cursor to the next position.

64

Page 65: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Catching SQLExceptionSQLException is not a checked exception,

so you may choose to ignore the example in writing the program.

65

Page 66: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Dynamically constructed queriesIt is usually necessary to create a query

dynamically. For example, you may have the following query:

statement.executeQuery("select * from student where firstName='"+name+"'");

Here, name is a value obtained from a JTextfield.

66

Page 67: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Problems of constructing a query from a stringThe first problem is that there is no

validation of the input field. For example, when a parameter is expected to be an integer, but a string is input.

There is a possibility of malicious attack. For example, if the user type in a value so that the name variable now has the value:

nobody'; delete from student; select * from student where firstName='nobody

67

Page 68: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Problems of constructing a query from a stringThen, the query in last example would

become:

select * from student where firstName=' nobody'; delete from student; select * from student where firstName='nobody'

Now, this is valid SQL statement but it will delete all rows in the table student.

68

Page 69: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Prepared statementsWe can solve this problem using

PreparedStatement.preparedStatement=connection.prepareSta

tement("select * from student where firstName=?");

Now, before you can use this statement to make a query, you need to set the unknown value specified by the ? in the above statement.

preparedStatement.setString(1,"Chan Tai Man");

This statement set the first unknown to be "Chan Tai Man".

69

Page 70: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Prepared statementsIf you invoke the following statement for

the above example:preparedStatement.setString(1," nobody'; delete from student; select * from student where firstName='nobody");

do you think that the rows in student will still be deleted?

The answer is no because using the setString method will allow Java to know that the input is just a string value to be passed to an SQL statement. It itself will not be part of the SQL statement. Therefore, if the query is executed, it will just look for student with this long name. It is very likely that this query will just return zero row.

70

Page 71: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Other methods of PreparedStatementsetInt(int index, int v) //set integer valuesetDouble(int index, double x) //set double

valuesetLong(int index, long x) //set longsetTimestamp(int index, Timestamp

time) //set timestampsetDate(int index, Date date) //set date

By using these methods, it is less likely to input a wrong type of data.

71

Page 72: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Other methods of PreparedStatementsOf course there are also statements to

execute query and update:ResultSet executeQuery();int executeUpdate();

72

Page 73: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Case studyAssume that we have the following table

created:create table student(id varchar(20) primary

key, name varchar(50), birthdate date);create table course(courseid varchar(15)

primary key, coursename varchar(50));create table study(id varchar(20), courseid

varchar(15), primary key(id,courseid));

73

Page 74: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Case studyWe now create an application which allows

the user to type in new student's record.You can find the source at:http://plbpc001.ouhk.edu.hk/~mt311f/

2010-sep/database/database/src/database/InsertStudent.java

74

Page 75: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Inserting a studentThe application has

three textfield for inputting the name, id and date of birth of the student.

If there is any error, a message will be display at the top of the window.

75

Page 76: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

AttributesJTextField name; for inputing the nameJTextField id; for inputing the idJTextField dob; for inputing the date of birthJLabel message; for displaying any error

messageJButton insert; for inserting the recordConnection conn; the database connectionPreparedStatement pre; the prepared

statement

76

Page 77: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Initialization of the database connectionClass.forName("com.mysql.jdbc.Driver");

conn=java.sql.DriverManager.getConnection("jdbc:mysql://127.0.0.1/mydata","usera","userapass");

pre=conn.prepareStatement("insert into student values(?,?,?)");

77

Page 78: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

The action listener of the buttonpublic void actionPerformed(ActionEvent e) {

try {

pre.setString(1, id.getText());

pre.setString(2, name.getText());

pre.setDate(3, new java.sql.Date(java.text.DateFormat.getDateInstance(java.text.DateFormat.SHORT, java.util.Locale.UK).parse(dob.getText()).getTime()));

pre.executeUpdate();

}

catch (Exception ee) {

message.setText("error");

ee.printStackTrace();

}

}78

Page 79: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Another application listing students' recordsList the courses studied by a particular

student.The textfield is for the user to type in the

name of a student.After the user has pressed the List button,

the courses he/she studies will be listed in the text area.

You can download the file at:http://plbpc001.ouhk.edu.hk/~mt311f/2010-

sep/database/database/src/database/ListCoursesStudied.java

79

Page 80: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

AttributesJTextField name; for the user to type in the

name of a studentJTextArea result; for the displaying of the

result.Connection conn; the database connectionPreparedStatement pre; the prepared

statement.

80

Page 81: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Database connectionThe same as previous applicaiton.The prepared statement is initialized this

way:

pre = conn.prepareStatement("select coursename, course.courseid from study, student,course where student.id=study.id and course.courseid=study.courseid and name=?");

81

Page 82: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

ActionListener of the button public void actionPerformed(ActionEvent e) {

try {

pre.setString(1, name.getText().trim());

ResultSet re=pre.executeQuery();

result.setText("");

while (re.next()) {

String coursename=re.getString(1);

String courseid=re.getString(2);

result.append(courseid+" "+coursename+"\n");

}

}

catch (Exception ee) {

}

}

82

Page 83: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Web programmingDynamic Web contents

Shopping web sitesNewsFacebooksYoutube

83

Page 84: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

CGICGI stands for Common Gateway Interface.It is not a programming language but an

interface that allows the Web server to invoke an external program.

The actual program can be written in any programming languages.

CGI programs are usually stored in a special directory on Web servers. For example: /cgi-bin.

Web servers redirect HTTP requests from end-users to appropriate CGI programs.

84

Page 85: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Disadvantages of CGIsIn CGI, a new process is started to handle

each HTTP request. The overhead of starting new processes is high. The performance of CGI suffers when many HTTP requests are received within a short period of time.

To improve performance, we can have a process perpetually running on the Web server. When a new HTTP request is received, the process uses a thread to handle it. This thread can be created new or selected from a thread pool. The overhead to handle a request is significantly lowered.

85

Page 86: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Java alternative to CGIServlets

A servlet is an object that receives a request and generates a response based on that request.

Before you can use servlets, you need a servlets enabled Web server.

One of the most popular servlet enabled web server is Tomcat.

86

Page 87: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Advantages of ServletsEfficient. No need to create a new process

for a request. A single copy of the servlet is used to serve multiple requests. A separate thread is used to serve a new request.

Powerful. Servlets can talk directly to the Web server. Servlets can also share data among each other. It is also easy to maintain session information.

Portable. Java is much more portable than other languages.

Inexpensive. There are many Java serlvet servers that are free.

87

Page 88: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Download Tomcat 6.0Download Tomcat 6.0 from

http://tomcat.apache.org/download-60.cgiAfter extracting the files, there should be a

folder named bin.This folder contains batch files with which

you can start up or shut down tomcat.Before you can start up tomcat, you need

to setup the JAVA_HOME environment variable pointing to the Java home.

startup.bat: the batch file to start up Tomcat.

shutdown.bat: the batch file to shutdown Tomcat.

88

Page 89: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Enabling Netbeans to create Web applicationsTool -> Plugins -> Available Plugins -> Java

Web ApplicationsAfter doing this, we can create web

applications using Netbeans.

89

Page 90: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

A simple servletAll servlets should be subclasses of

HttpServlet.

90

Page 91: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Methods of HttpServletvoid doGet(HttpServletRequest req,

HttpServletResponse resp)This method will be called by the server to

allow a servlet to handle a GET request. Overriding this method to support a GET

request.Input should be read from req and output

should be written to resp.

91

Page 92: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Methods of HttpSerlvetvoid init(ServletConfig config)

Called by the servlet container to indicate to a servlet that the servlet is being placed into service.

We should put initialization code to this method.

If this method is overridden, we should call the super.init(config) method first.

92

Page 93: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Methods of HttpServletvoid doPost(HttpServletRequest req,

HttpServletResponse resp)Similar to doGet except that this method is

used to serve POST requests.

93

Page 94: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

HttpServletRequestThis class encapsulates all the request for

the servlet service.

94

Page 95: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Methods of HttpServletRequestCookie[] getCookies()

returns an array containing all of the cookies the client sent with this request.

String getHeader(String st)returns the value of the specified request

header as a string.String getMethod()

Returns the name of the HTTP method with which this request was made, for example, GET, POST,..

String getQueryString()Returns the query string that is contained in

the request URL.95

Page 96: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Methods of HttpServletRequestHttpSession getSession()

Returns the current session associated with this request.

String getParameter(String name)returns the value of a request parameter as a

String, or null if the parameter does not exist. Parameters are contained in the query string or posted form data.

96

Page 97: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

HttpSerlvetResponsevoid addCookie(Cookie c)

Add the specified cookie to the response.void addHeader(String name, String value)

Adds a response header with the given name and value.

ServletOutputStream getOutputStream()return an output stream suitable for writing

binary data in the response.PrintWriter getWriter()

Returns a PrintWriter object that can send character text to the client.

97

Page 98: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

HttpSerlvetResponsevoid setContentType(String type)

Set the content type of the response being sent to the client.

98

Page 99: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

A simple servletpackage test;

public class HelloServlet extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter();

out.println("Hello, world!"); out.close(); }

}

99

Page 100: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Connection to databaseConsider the following servlet's doGet

method:

public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {Class.forName("com.mysql.jdbc.Driver");conn=java.sql.DriverManager.getConnection("jdbc:mysql://127.0.0.1/mydata","usera","userapass");

pre=conn.prepareStatement("select name from student");..... //do something for the code

100

Page 101: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Disadvantage of the previous methodThe connection is made everytime when a

request comes in. This would be very inefficient.

A more efficient code would be to include the code in init method of the servlet.

101

Page 102: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

HTTP Sessions HTTP is a stateless protocol. This means

that requests to a server are independent of each other. The protocol does not store information regarding a previous requests from the same user.

This would be a problem as http requests are most of the time related with each other.

For example, when a user is visiting an online shop, there is a need to remember what he/she has put into the shopping cart.

102

Page 103: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Keeping session informationWe can use the concept of a session to

refer to a sequence of requests that are related to each other.

Information for this sequence of requests is called session information.

For example, items in a shopping cart, user name etc. are typical session information.

103

Page 104: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Storing session informationThere are a number of ways to store

session information:Using hidden values in an HTML form.

If the servlet wants to remember a value in subsequent requests from the Web client, the servlet can include a hidden input value in the response:<input type="hidden" name="myname"

value="myvalue">In order for this method to work, this input value

has to be inside a form. This input value will be submit to the server when the form is submit.

Using the embedded query string in an URL.The other method is to embed a query string in an

URL. For example:<a href="abc.html? myname=myvalue”>a link</a>

In this way, the query string would be submit to the web server when this link is clicked.

104

Page 105: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Storing session informationUsing cookies

A cookie, is a piece of text stored by a user's web broswer. A cookie can be used for authentication, storing site preferences, shopping cart contents, the identifier for a server-based session.

A cookie consists of one or more name-value pairs containing bits of information, which may be encrypted.

The cookie is sent as an HTTP header by a web server to a web browser and then sent back unchanged by the browser each time it accessess that server.

105

Page 106: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Session tracking with cookiesCookies are created by Web servers to be

stored on the client computer’s hard disk as small text files. A cookie contains the following information.

1 name of the cookie 2 value of the cookie 3 expiry date 4 domain name of the website 5 path information.

106

Page 107: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Drawbacks of using cookiesOne drawback to using cookies is that they

reside on a computer and do not follow the end-user when he or she uses another computer. This drawback concerns convenience. There are more serious drawbacks that concern security.

More and more computers refuse to accept cookies.

Cookies may lead to privacy problem.Cookie theft, cookie poisoning etc are

possible attack to cookies.

107

Page 108: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Creating and returning cookiesThe servlet can create a cookie by calling

the Cookie constructor with the name and the value of the cookie:Cookie cookiename=new

Cookie("cookiename",cookiname);To set a cookie:

response.addCookie(cookiename);The cookie would be sent back to the client.

108

Page 109: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Reading cookie valuesWhen a Web client sends a request to the

servlet, the servlet can call the getCookies( ) method on the HttpServletRequest object. The call returns an array of Cookie objects stored in the client. The servlet iterates through the array to find a cookie with a matching name.

Cookie[] cookies=rquest.getCookies();for (int i=0;i<cookies.length;i++) {

cookies[i].getName(); //for the name;cookies[i].getValue(); //for the value;

}109

Page 110: Li Tak Sing Lectures 7-8-9 COMPS311F 1. Remote Method Invocation(RMI) For distributed computing. A Java object on one system can invoke a method in an.

Modifying cookie valuesYou can use the setValue method of Cookie

to chang the value of the cookie:

if (cookies[i].getName().equals("abc")) {cookies[i].setValue("ddd");response.addCookie(cookies[i]);

}

110