Download presentation
Presentation is loading. Please wait.
Published byDennis Hutchinson Modified over 9 years ago
1
Li Tak Sing Lectures 7-8-9 COMPS311F 1
2
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
3
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
4
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
5
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
6
Operations of RMI 6
7
1. 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
8
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
9
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
10
RMI Registry java.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
11
Methods of java.rmi.registry.Registry void 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
12
Developing RMI Applications 1. 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
13
Developing RMI Applications 2. 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
14
Developing RMI Applications 3. 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
15
Developing RMI Applications 4. 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
16
A simple RMI server that adds two integers. You can download the code at: http://plbpc001.ouhk.edu.hk/~mt311f/examples/mt311201 0/src/rmi.zip The server has just one method: public int sum(int i,int j) The method would return the sum of i and j. 16
17
RMIAddServer public interface RMIAddServer extends Remote { public int sum(int i, int j) throws RemoteException; //this method will return the sum of the two integers. } 17
18
RMIAddServerImp public class RMIAddServerImp extends UnicastRemoteObject implements RMIAddServer { public RMIAddServerImp() throws RemoteException { } public int sum(int i, int j) throws RemoteException { return i+j; } 18
19
RMIAddServerImp public static void main(String st[]) throws RemoteException { RMIAddServerImp obj=new RMIAddServerImp(); Registry registry=LocateRegistry.getRegistry(); registry.rebind("add", obj); } 19
20
ADDClient public 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
21
Start the server execute 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
22
RMI vs. Socket-Level Programming RMI 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
23
RMI callbacks In 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
24
Passing the client to the server The 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
25
Implementation of the client The 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
26
Implementation of the server The 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
27
A Chat server using RMI You can download the program at http://plbpc001.ouhk.edu.hk/~mt311f/examples/mt311201 0/src/r.zip The server is stored in the package RMIChat In 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 server ChatServerImp: implementation of the chat server ChatClient: interface for the chat client ChatClientImp: implementation of the chat client 27
28
ChatServer public 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
29
ChatServerImp It contains a JFrame and a JTextArea for the displaying all messages from the clients. The bottom line displays all connected clients. 29
30
Declaration of ChatServerImp public class ChatServerImp extends UnicastRemoteObject implements ChatServer{..... } 30
31
Some Attributes of ChatServerImp Vector clients; //this stores all connected clients 31
32
Some Methods of ChatServerImp public void send(String st) throws RemoteException { Vector problem = new Vector (); textarea.append(st+"\n"); synchronized (clients) { for (ChatClient c : clients) { try { c.toClient(st); } catch (Exception e) { problem.add(c); } 32
33
Some Methods of ChatServerImp } for (ChatClient c : problem) { clients.remove(c); } displayClients(); } 33
34
Some Methods of ChatServerImp public void connect(ChatClient c) throws RemoteException { clients.add(c); displayClients(); } 34
35
Some Methods of ChatServerImp public void disconnect(ChatClient c) throws RemoteException { clients.remove(c); displayClients(); } 35
36
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
37
ChatClient public 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
38
ChatClientImp The 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
39
ChatClientImp There 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
40
Declaration of ChatClientImp public class ChatClientImp extends UnicastRemoteObject implements ChatClient {... 40
41
Some Attributes of ChatClientImp JTextField 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
42
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
43
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
44
The action listener of the connect button } else { connect.setText("connect"); server.disconnect(ChatClientImp.this); } } catch (NotBoundException ex) { } 44
45
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
46
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
47
Some features of this RMI server There 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
48
Problems of the RMI ChatServer Although 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
49
The java.rmi.server.Unreferenced interface This 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
50
The java.rmi.server.Unreferenced interface There 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
51
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
52
But there is a delay before unreferenced is called Note that the unreferenced method would only be invoked for a delay of 10 minutes after all referencing clients have quit. 52
53
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
54
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
55
Changes to ChatServerImp The connect method is changed as following: public Contact connect(ChatClient c) throws RemoteException { clients.add(c); displayClients(); return new ContactImp(c); } 55
56
Changes to ChatClient The 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
57
Database programming JDBC (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
58
ODBC When 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
59
JDBC Similarly, 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
60
Using JDBC Step 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
61
Using JDBC Step 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/jdata base","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
62
Using JDBC Step 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 statement Now we create a statement using the Connection object. Statement statement = connection.createStatement(); 62
63
Using JDBC Step 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
64
Using JDBC Processing 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
65
Catching SQLException SQLException is not a checked exception, so you may choose to ignore the example in writing the program. 65
66
Dynamically constructed queries It 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
67
Problems of constructing a query from a string The 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
68
Problems of constructing a query from a string Then, 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
69
Prepared statements We can solve this problem using PreparedStatement. preparedStatement=connection.prepareStatement("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
70
Prepared statements If 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
71
Other methods of PreparedStatement setInt(int index, int v) //set integer value setDouble(int index, double x) //set double value setLong(int index, long x) //set long setTimestamp(int index, Timestamp time) //set timestamp setDate(int index, Date date) //set date By using these methods, it is less likely to input a wrong type of data. 71
72
Other methods of PreparedStatements Of course there are also statements to execute query and update: ResultSet executeQuery(); int executeUpdate(); 72
73
Case study Assume 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
74
Case study We 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
75
Inserting a student The 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
76
Attributes JTextField name; for inputing the name JTextField id; for inputing the id JTextField dob; for inputing the date of birth JLabel message; for displaying any error message JButton insert; for inserting the record Connection conn; the database connection PreparedStatement pre; the prepared statement 76
77
Initialization of the database connection Class.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
78
The action listener of the button public 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.SH ORT, java.util.Locale.UK).parse(dob.getText()).getTime())); pre.executeUpdate(); } catch (Exception ee) { message.setText("error"); ee.printStackTrace(); } 78
79
Another application listing students' records List 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
80
Attributes JTextField name; for the user to type in the name of a student JTextArea result; for the displaying of the result. Connection conn; the database connection PreparedStatement pre; the prepared statement. 80
81
Database connection The 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
82
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
83
Web programming Dynamic Web contents Shopping web sites News Facebooks Youtube 83
84
CGI CGI 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
85
Disadvantages of CGIs In 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
86
Java alternative to CGI Servlets 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
87
Advantages of Servlets Efficient. 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
88
Download Tomcat 6.0 Download Tomcat 6.0 from http://tomcat.apache.org/download-60.cgi After 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
89
Enabling Netbeans to create Web applications Tool -> Plugins -> Available Plugins -> Java Web Applications After doing this, we can create web applications using Netbeans. 89
90
A simple servlet All servlets should be subclasses of HttpServlet. 90
91
Methods of HttpServlet void 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
92
Methods of HttpSerlvet void 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
93
Methods of HttpServlet void doPost(HttpServletRequest req, HttpServletResponse resp) Similar to doGet except that this method is used to serve POST requests. 93
94
HttpServletRequest This class encapsulates all the request for the servlet service. 94
95
Methods of HttpServletRequest Cookie[] 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
96
Methods of HttpServletRequest HttpSession 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
97
HttpSerlvetResponse void 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
98
HttpSerlvetResponse void setContentType(String type) Set the content type of the response being sent to the client. 98
99
A simple servlet package 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
100
Connection to database Consider 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:mys ql://127.0.0.1/mydata","usera","userapass"); pre=conn.prepareStatement("select name from student");..... //do something for the code 100
101
Disadvantage of the previous method The 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
102
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
103
Keeping session information We 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
104
Storing session information There 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: 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 link In this way, the query string would be submit to the web server when this link is clicked. 104
105
Storing session information Using 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
106
Session tracking with cookies Cookies 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
107
Drawbacks of using cookies One 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
108
Creating and returning cookies The 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
109
Reading cookie values When 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
110
Modifying cookie values You 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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.