Vous êtes sur la page 1sur 105

Java Servlets

Servlet

A servlet is a web component, managed by a container, that generates dynamic content. It is a server-side program written in Java. After writing the source code, it has to be compiled into a class file, like any Java program. Whenever a HTTP request comes, requesting for the execution of this Servlet, the class file is interpreted by the Java Virtual Machine (JVM). This produces HTML output and is sent back to the browser in the form of HTTP response.
2

Why Servlets?
Web pages with dynamic content Easy coordination between Servlets to make Web applications Containers support many features

Sessions, persistence, resource management (e.g., database connections), security, etc.

Where are Servlets?


Static File system

HTTP

Web Server Dynamic Servlet Server

Ex : Tomcat = Web Server + Servlet Server

Servlet job

Read explicit data sent by client (form data) Read implicit data sent by client (request headers) Generate the results Send the explicit data back to client (HTML) Send the implicit data to client (status codes and response headers)

When Servlets?
Receive Request for Servlet S Loaded when first used, or after modified no

Is S loaded? yes Is S current? yes Forward Request to S

no (re)Load S Servlets die when Servlet Server dies


6

CGI Scripts

CGI stands for Common Gateway Interface


Client sends a request to server Server starts a CGI script Script computes a result for server and quits Server returns response to client Another client sends a request Server starts the CGI script again
7

client

server
script

client

Servlets

A servlet is like an applet, but on the server side


Client sends a request to server Server starts a servlet Servlet computes a result for server and does not quit Server returns response to client Another client sends a request Server calls the servlet again client

server
servlet

client

Servlets vs. CGI scripts

Running a servlet doesnt require creating a separate process each time (threads used) A servlet stays in memory, so it doesnt have to be reloaded each time There is only one instance handling multiple requests, not a separate instance for every request A variety of different languages were used to build CGI programs. These included C, C++, and Perl. Where as Servlet are coded in java
9

Servlets vs. CGI scripts


CGI suffered serious performance problems. It was expensive in terms of processor and memory resources to create a separate process for each client request. It was also expensive to open and close database connections for each client request. In addition, the CGI programs were not platform-independent. Servlet is platformindependent.

10

What are the advantages of servlets?

Portability

Portable across operating systems and across web servers.

Power

Harness the full power of the core Java APIs: networking and URL access, multithreading, image manipulation, data compression, JDBC.

Efficiency & Endurance

Memory resident, so invocation highly efficientno process to spawn or interpreter to invoke.


11

What are the advantages of servlets? (Contd)

Safety

Support safe programming since inherit Javas strong type safety, exception-handling mechanism.

Security

the Java security manager on the server enforces a set of restrictions to protect the resources on a server machine Code is clean, object-oriented, modular, and simple (i.e.. Session tracking, cookie).

Elegance

Integration

Tightly integrated with the servertranslate file paths, perform logging, check authorization, and MIME type mapping.
12

What are the disadvantages of servlets?


Developers MUST know JAVA Web Administrator will need to learn how to install and maintain Java Servlets Less choice of languages (CGI scripts can be in any language) Tedious uses of out.println() statements

Can be remedied by using Java Server Page (JSP)

13

Servlet Container

A servlet runs inside a Servlet container. A Servlet container is the hosting environment for Java Servlets. A compiler plus run-time hosting environment for Servlets.

Ex : Tomcat is a Servlet container which runs inside a Web server, Apache.


14

What is HTTP

Hypertext Transfer Protocol is used to describe how HTML documents are sent over the Internet. It is stateless protocol HTTP Request Model

A client application, such as web browser opens a socket to the web servers HTTP port (80) Through the connection, the client writes an ASCII text request line, followed by zeros and more HTTP headers, an empty line, and any data that accompanies the request The web server parses the request and locates the specified resource The server writes a copy of the resource to the socket, where its read by the client The server closes the connection
15

HTTP Request methods


Method Description

GET
HEAD

A simple request to retrieve identified in the URI


Same as GET, except server doesnt return the requested document. The server returns only the status line and headers A request for the server to accept data that will be written to the clients output stream A request for the server to store the data in the request as the new contents of the specified URI A request for the server to delete the resource named in the URI

POST PUT DELETE

OPTIONS
TRACE CONNECT

A request for information about what request methods the server supports
A request for the web server to echo the HTTP request and its headers A documented but currently unimplemented method reserved for use with a tunneling proxy.
16

Flow of execution in the Servlet Environment


1. 2. 3.

4.

The browser sends an HTTP request to the Web server for executing a Servlet. The Web server hands it over to the servlet container, after providing the appropriate execution environment. The Servlet container loads and executes the Servlet (.class file of the Servlet) by interpreting its contents via the JVM. The result is usually some HTML output. This HTML output is sent back to the Web browser via the web server, as a part of the HTTP response.

17

Apache

Apache is a very popular server

66% of the web sites on the Internet use Apache


Full-featured and extensible Efficient Robust Secure (at least, more secure than other servers) Up to date with current standards Open source Free

Apache is:

18

Ports

A port is a connection between a server and a client


Ports are identified by positive integers A port is a software notion, not a hardware notion, so there may be very many of them Typical port numbers:

A service is associated with a specific port

21FTP, File Transfer Protocol 22SSH, Secure Shell 25SMTP, Simple Mail Transfer Protocol These are the ports 53DNS, Domain Name Service of most interest to us 80HTTP, Hypertext Transfer Protocol 8080HTTP (used for testing HTTP) 7648, 7649CU-SeeMe
19

Tomcat

Tomcat is the Servlet Engine than handles servlet requests for Apache

Tomcat is a helper application for Apache Its best to think of Tomcat as a servlet container

Its easier to install Tomcat standalone than as part of Apache

By itself, Tomcat can handle web pages, servlets, and JSP

Apache and Tomcat are open source (and therefore free)


20

21

Servlet lifecycle

Servlet initialization -init() method

Happens once in lifecycle

Service client requests-service() method

happens once for every client request

Servlet destruction- destroy() method

happens once in life cycle

22

Servlet Life Cycle

23

Servlet Life Cycle


A user enters a Uniform Resource Locator (URL) to a Web browser. The browser then generates an HTTP request for this URL. This request is then sent to the appropriate server. This HTTP request is received by the Web server. The server maps this request to a particular servlet. The servlet is dynamically retrieved and loaded into the address space of the server.

24

Servlet Life Cycle

The server invokes the init( ) method of the servlet. This method is invoked only when the servlet is first loaded into memory. It is possible to pass initialization parameters to the servlet so it may configure itself. The server invokes the service( ) method of the servlet. This method is called to process the HTTP request. You will see that it is possible for the servlet to read data that has been provided in the HTTP request. It may also formulate an HTTP response for the client.
25

Servlet Life Cycle

The servlet remains in the servers address space and is available to process any other HTTP requests received from clients. The service( ) method is called for each HTTP request. Finally, the server may decide to unload the servlet from its memory. The algorithms by which this determination is made are specific to each server. The server calls the destroy( ) method to relinquish any resources such as file handles that are allocated for the servlet. Important data may be saved to a persistent store. The memory allocated for the servlet and its objects can then be garbage collected.
26

Installation of Apache Tomcat


First install j2sdk1.4.2_13 for access of Java classes & interfaces as the servlet is written in Java language. Set the environment variable PATH to c:\j2sdk1.4.2_13\bin; c:\j2sdk1.4.2_13\lib Next install Tomcat Create a new SYSTEM environment variable CLASSPATH to c:\Program Files\Apache Group\Tomcat 4.1\common\lib\servlet.jar Alternatively, you can specify this class file when you compile the servlets. For example, the following command compiles the first servlet example: javac HelloServlet.java -classpath "C:\Program Files\Apache Tomcat 4.0\common\lib\servlet.jar" To execute already provided examples of servlet In Internet Explorer add the URL http://localhost:8080
27

Execution in Tomcat

Create .java file in c:\j2sdk1.4.2_13\bin Compile it there using javac filename.java Copy the .class file to Tomcat server. C:\Program Files\Apache Group\Tomcat 4.1\webapps\examples\WEB-INF\classes\ Start the Tomcat server and minimize the window. Open Internet Explorer and in the URL enter http://localhost:8080/examples/servlet/filename
28

Steps to create Servlet


Create and compile the servlet source code. Start Tomcat. Start a Web browser and request the servlet.

29

Create and compile the servlet source code


create a file named HelloServletpro.java that contains the following program import java.io.*; import javax.servlet.*; public class HelloServletpro extends GenericServlet { public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>Hello welcome to servlet programming!"); pw.close(); } } Copy the .class file to Tomcat server. C:\Program Files\Apache Group\Tomcat 4.1\webapps\examples\WEB-INF\classes\

30

Explanation of program

First, note that it imports the javax.servlet package. This package contains the classes and interfaces required to build servlets. Next, the program defines HelloServlet as a subclass of GenericServlet. The GenericServlet class provides functionality that makes it easy to handle requests and responses. Inside HelloServet, the service( ) method (which is inherited from GenericServlet) is overridden. This method handles requests from a client. Notice that the first argument is a ServletRequest object. This enables the servlet to read data that is provided via the client request. The second argument is a ServletResponse object. This enables the servlet to formulate a response for the client. The call to setContentType( ) establishes the MIME type of the HTTP response. In this program, the MIME type is text/html. This indicates that the browser should interpret the content as HTML source code. Next, the getWriter( ) method obtains a PrintWriter. Anything written to this stream is sent to the client as part of the HTTP response. 31 Then println( ) is used to write some simple HTML source code as the HTTP response.

Start Tomcat
As explained, to start Tomcat, select Start Tomcat in the Start | Programs menu, or run startup.bat from the C:\Program Files\Apache Tomcat 4.0\bin\directory.

32

Start a Web Browser and Request the Servlet

Start a Web browser and enter the URL shown here:

http://localhost:8080/examples/servlet/HelloS ervletpro

Alternatively, you may enter the URL shown here:

http://127.0.0.1:8080/examples/servlet/Hello Servletpro

33

Servlet Architecture

javax.servlet.Servlet interface javax.servlet.GenericServlet and javax.servlet.http.HttpServlet class Sun has provided a Java class called HttpServlet having methods for initialization, servicing, and destruction of Servlets. A new Servlet has to be written by extending from HttpServlet class.
34

The Servlet API


javax.servlet javax.servlet.http

35

The javax.servlet Package

36

The javax.servlet Package

37

Servlet Interface

38

ServletConfig Interface

39

ServletContext Interface

40

ServletRequest Interface

41

ServletRequest Interface

42

ServletRequest Interface

43

ServletResponse Interface

44

SingleThreadModel Interface
only a single thread will execute the service( ) at a time First, it can create several instances of the servlet. Second, it can synchronize access to the servlet No constant, no methods declared

45

GenericServlet Class
Basic life cycle of servlet Implements servlet and servletconfig interface void log(String s) void log(String s, Throwable e)

a method to append a string to the server log file

46

ServletInputStream Class

Extends InputStream Implemented by the server It defines the default constructor. int readLine(byte[ ] buffer, int offset, int size) throws IOException Here, buffer is the array into which size bytes are placed starting at offset. The method returns the actual number of bytes read or 1 if an end-ofstream condition is encountered.

47

ServletOutputStream Class
extends OutputStream implemented by the server A default constructor is defined. the print( ) and println( ) methods

48

Servlet Exception Classes


javax.servlet defines two exceptions. The ServletException, which indicates that a servlet problem has occurred. The UnavailableException, which extends ServletException. It indicates that a servlet is unavailable.

49

Servlets

A servlet is any class that implements the javax.servlet.Servlet interface


In practice, most servlets extend the javax.servlet.http.HttpServlet class Some servlets extend javax.servlet.GenericServlet instead

Servlets, like applets, usually lack a main method, but must implement or override certain other methods
50

Example
<html> <body> <center> <form name=f1" method="post" action="http://localhost:8080/examples/servlet/PostParametersServlet"> <table> <tr> <td><B>Employee</td> <td><input type=textbox name="e" size="25" value=""></td> </tr> <tr> <td><B>Phone</td> <td><input type=textbox name="p" size="25" value=""></td> </tr> </table> <input type=submit value="Submit"> </body> </html>

51

Example
import java.io.*; import java.util.*; import javax.servlet.*; public class PostParametersServlet extends GenericServlet { public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { // Get print writer. PrintWriter pw = response.getWriter(); // Get enumeration of parameter names. Enumeration e = request.getParameterNames(); // Display parameter names and values. while(e.hasMoreElements()) { String pname = (String)e.nextElement(); pw.print(pname + " = "); String pvalue = request.getParameter(pname); pw.println(pvalue); } pw.close(); } }

PostParametersServlet.java

52

How to Run
Compile the servlet and perform these steps to test this example: 1. Start Tomcat (if it is not already running). 2. Display the Web page in a browser. 3. Enter an employee name and phone number in the text fields. 4. Submit the Web page.

53

javax.servlet.http Package

54

HttpServletRequest

55

56

57

HttpServletResponse

58

59

HttpSession

All of these methods throw an IllegalStateException if the session has already been invalidated

60

61

HttpSessionBindingListener
Is implemented by objects that need to be notified when they are bound to or unbound from an HTTP session. void valueBound(HttpSessionBindingEvent e) void valueUnbound(HttpSessionBindingEvent e) Here, e is the event object that describes the binding.

62

Cookie Class

A cookie is stored on a client and contains state information. Cookies are valuable for tracking user activities A servlet can write a cookie to a users machine via the addCookie( ) method of the HttpServletResponse interface Cookie data includes The name of the cookie The value of the cookie The expiration date of the cookie The domain and path of the cookie Constructor

Cookie(String name, String value)

63

Cookie Class

64

65

HttpServlet Class

It extends GenericServlet class

66

67

HttpSessionEvent Class
It encapsulates session events It extents EventObject and is generated when a change occurs to the session HttpSessionEvent(HttpSession session)

session is the source of the event


It returns the session in which the event occurred.

HttpSession getSession( )

68

HttpSessionBindingEvent Class
It extends HttpSessionEvent HttpSessionBindingEvent(HttpSession session, String name) HttpSessionBindingEvent(HttpSession session, String name, Object val)

Here, session is the source of the event and name is the name associated with the object that is being bound or unbound. If an attribute is being bound or unbound, its value is passed in val.

69

methods

String getName( )

obtains the name that is being bound or unbound


obtains the session to which the listener is being bound or unbound obtains the value of the attribute that is being bound or unbound

HttpSession getSession( )

Object getValue( )

70

Servlets

A servlet is any class that implements the javax.servlet.Servlet interface


In practice, most servlets extend the javax.servlet.http.HttpServlet class Some servlets extend javax.servlet.GenericServlet instead

Servlets, like applets, usually lack a main method, but must implement or override certain other methods
71

Important servlet methods, I

When a servlet is first started up, its init(ServletConfig config) method is called init should perform any necessary initializations init is called only once, and does not need to be thread-safe (syncronization not required) Every servlet request results in a call to service(ServletRequest request, ServletResponse response) service calls another method depending on the type of service requested Usually you would override the called methods of interest, not service itself service handles multiple simultaneous requests, so it and the methods it calls must be thread safe (syncronization required)

When the servlet is shut down, destroy() is called destroy is called only once, but must be thread safe (because other threads may still be running)

72

HTTP requests

When a request is submitted from a Web page, it is almost always a GET or a POST request The HTTP <form> tag has an attribute action will be the URL,method whose value can be "get" or "post" The "get" action results in the form information being put after a ? in the URL

Example: http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF8&q=servlets The & separates the various parameters Only a limited amount of information can be sent this way
73

"put" can send large amounts of information

Important servlet methods, II

The service method dispatches the following kinds of requests: DELETE, GET, HEAD, OPTIONS, POST, PUT, and TRACE

A GET request is dispatched to the doGet(HttpServletRequest request, HttpServletResponse response) method A POST request is dispatched to the doPost(HttpServletRequest request, HttpServletResponse response) method

These are the two methods you will usually override doGet and doPost typically do the same thing, so usually you do the real work in one, and have the other just call it

public void doGet(HttpServletRequest request, HttpServletResponse response) { doPost(request, response); }

74

HTTP requests & responses with respect to Servlets


The browsers HTTP request is sent to the server. The servlets doGet() method receives this request as a parameter. Similarly, when the server needs to send back an HTTP response, it populates the corresponding attributes or calls methods in the other parameter HttpServletResponse, which is used to send back information to the browser in the form of an HTTP response.

75

Hello World Example A (.java)


import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title>Hello World!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello World!</h1>"); out.println("</body>"); out.println("</html>"); } }

http://localhost:8080/examples/servlet/HelloServlet

76

The superclass

public class HelloServlet extends HttpServlet { Every class must extend GenericServlet or a subclass of GenericServlet GenericServlet is protocol independent, so you could write a servlet to process any protocol In practice, you almost always want to respond to an HTTP request, so you extend HttpServlet A subclass of HttpServlet must override at least one method, usually one doGet, doPost, doPut, doDelete, init and destroy, or getServletInfo
77

The doGet method

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { This method services a GET request The method uses request to get the information that was sent to it The method does not return a value; instead, it uses response to get an I/O stream, and outputs its response Since the method does I/O, it can throw an IOException Any other type of exception should be encapsulated as a ServletException The doPost method works exactly the same way

78

Parameters to doGet

Input is from the HttpServletRequest parameter Output is via the HttpServletResponse object, which we have named response

I/O in Java is very flexible but also quite complex, so this object acts as an assistant

79

Using the HttpServletResponse


The second parameter to doGet (or doPost) is HttpServletResponse response Everything sent via the Web has a MIME type The first thing we must do with response is set the MIME type of our reply: response.setContentType("text/html");

This tells the client to interpret the page as HTML

Because we will be outputting character data, we need a PrintWriter, handily provided for us by the getWriter method of response: PrintWriter out = response.getWriter(); Now were ready to create the actual page to be 80 returned

Using the PrintWriter


From here on, its just a matter of using our PrintWriter, named out, to produce the Web page First we create a header string:
String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; This line is technically required by the HTML spec Browsers mostly dont care, but HTML validators do care

Then use the println method of out one or more times


out.println(docType + "<HTML>\n" + "<HEAD> ... </BODY></HTML>");

81

Input to a servlet

A GET request supplies parameters in the form URL?name=value&name=value&name=value Actual spaces in the parameter values are encoded by + signs Other special characters are encoded in hex; for example, an ampersand is represented by %26 Parameter names can occur more than once, with different values A POST request supplies parameters in the same syntax, only it is in the body section of the request and is therefore harder for the user to see
82

Getting the parameters

Input parameters are retrieved via messages to the HttpServletRequest object request

Most of the interesting methods are inherited from the superinterface ServletRequest Returns an Enumeration of the parameter names If no parameters, returns an empty Enumeration Returns the value of the parameter name as a String If the parameter doesnt exist, returns null If name has multiple values, only the first is returned Returns an array of values of the parameter name If the parameter doesnt exist, returns null

public Enumeration getParameterNames()


public String getParameter(String name)


public String[] getParameterValues(name)



83

Example of input parameters


public void doGet(HttpServletRequest request, HttpServletResponse response) { ... ... out.println("<H1>Hello"); String names[] = request.getParameterValues("name"); if (names != null) for (int i = 0; i < names.length; i++) out.println(" " + names[i]); out.println("Done"); }
84

Java review: Data from Strings


All parameter values are retrieved as Strings Frequently these Strings represent numbers, and you want the numeric value int n = new Integer(param).intValue(); double d = new Double(param).doubleValue(); byte b = new Byte(param).byteValue(); Similarly for short, float, and long These can all throw a NumberFormatException, which is a subclass of RuntimeException boolean p = new Boolean(param).booleanValue(); char c = param.charAt(0);

85

form.html Example
<HTML> <HEAD> <TITLE>Introductions</TITLE> </HEAD> <BODY> <FORM METHOD=GET ACTION="http://localhost:8080/examples/servlet/Hello"> If you don't mind me asking, what is your name? <INPUT TYPE=TEXT NAME="name"><P> <INPUT TYPE=SUBMIT> </FORM> </BODY> </HTML>
form.html
86

Hello.java Example
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Hello extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); String name = req.getParameter("name"); out.println("<HTML>"); out.println("<HEAD><TITLE>Hello, " + name + "</TITLE></HEAD>"); out.println("<BODY>"); out.println("Hello, " + name); out.println("</BODY></HTML>");
87

Handling HTTP Get Request Servlet Example 1 (.html file)


<html> <head> <title>Servlet Example Using an Input Form</title> </head>

<body> <h1>Forms Example Using Servlets</h1> <form action=http://localhost:8080/examples/servlet/EmailServl et> Enter your email ID: <input type=text name=email> <input type=submit> </form> </body> </html>
form2.html
88

Handling HTTP Get Request Servlet Example 1 (.java file)


import import import import java.io.*; java.net.*; javax.servlet.*; javax.servlet.http.*; public class EmailServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String email; email = request.getParameter(email); response.setContentType(text/html); PrintWriter out = response.getWriter(); out.println(<html>); out.println(<head>); out.println(<title>Servlet Example</title>); out.println(</head>); out.println(<body>); out.println(<p>The email ID you have entered is :+email+</p>); out.println(</body>); out.println(</html>); out.close();
89

EmailServlet.java

Servlet Example 2 (.java file)


import import import import java.io.*; java.net.*; javax.servlet.*; javax.servlet.http.*; public class CurrencyConvertor extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(text/html); PrintWriter out = response.getWriter(); out.println(<html>); out.println(<head>); out.println(<title>Dollars to Rupees Conversion Chart</title>); out.println(</head>); out.println(<body>); out.println(<h1>Currency Conversion Chart</h1>); out.println(<table border=1 cellpadding=3 cellspacing=0>); out.println(<tr>); out.println(<th>Dollars</th>); out.println(<th>Rupees</th>); out.println(</tr>); for (int dollars=1; dollars<=50; dollars++) { int rupees=dollars*40; out.println(<tr>+<td align=right>+dollars+</td>+ <td align=right>+rupees+</td>+</tr>); } out.println(</table>); out.println(</body>); out.println(</html>); out.close();

C:\j2sdk1.4.2_13\bin\CurrencyConvertor.java

90

Handling HTTP Post Request Servlet Example 3 (.html file)


<html> <body> <center> <form name="Form1" method="post" action="http://localhost:8080/examples/servlet/ColorPostServlet"> <B>Color:</B> <select name="color" size="1"> <option value="Red">Red</option> <option value="Green">Green</option> <option value="Blue">Blue</option> </select> <br><br> <input type=submit value="Submit"> </form> </body> </html>

Form3.html

91

Handling HTTP Post Request Servlet Example 3 (.java file)


import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ColorPostServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String color = request.getParameter("color"); response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>The selected color is: "); pw.println(color); pw.close(); } }

ColorPostServlet.java

92

Using Cookies

93

Cookie
What is a cookie? A cookie is a piece of textual information Send by the Web server to the client browser Every time the browser visits the Web site again, the cookie is sent unchanged back to the server

94

Cookie

A cookie is a string upto 4K characters that you tell the Web browser to store on a visitors hard drive. Cookies give you a way to store information about the site visitor that can retrieve each time the visitor returns to the site so long as the visitor uses the same Web browser and computer system. Each Web browser type stores all cookie data in a single file unique to the browser.

Without cookies there is no way of determining what happened the last time the visitor came to the site or even if the visitor has ever been to your site before.
95

Benefits of Cookies

Identification of a user

E-commerce Poll Portals Personal Views Useful for sites that dont require high security

Customizing a site

Avoiding login

96

Drawbacks of Cookies
User can deny cookies in his Web browser Might be a privacy thread

E.g. search engines remember user specific search topics

97

Handling cookies using Servlets (cookie.html)


<html> <body> <center> <form name="Form1" method="post" action="http://localhost:8080/examples/servlet/AddCookieSe rvlet"> <B>Enter a value for MyCookie:</B> <input type=textbox name="data" size=25 value=""> <input type=submit value="Submit"> </form> </body> </html>
98

Handling cookies using Servlets (AddCookieServlet.java)


import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class AddCookieServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get parameter from HTTP request. String data = request.getParameter("data"); // Create cookie. Cookie cookie = new Cookie("MyCookie", data); // Add cookie to HTTP response. response.addCookie(cookie); // Write output to browser. response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>MyCookie has been set to"); pw.println(data); pw.close(); } }

99

Handling cookies using Servlets (GetCookiesServlet.java)


import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class GetCookiesServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get cookies from header of HTTP request. Cookie[] cookies = request.getCookies(); // Display these cookies. response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>"); for(int i = 0; i < cookies.length; i++) { String name = cookies[i].getName(); String value = cookies[i].getValue(); pw.println("name = " + name + "; value = " + value); } pw.close(); } }

100

Session Tracking

101

Session Tracking

HTTP is a stateless protocol. Each request is independent of the previous one. However, in some applications, it is necessary to save state information so that information can be collected from several interactions between a browser and a server. Sessions provide such a mechanism. Session state is shared among all the servlets that are associated with a particular client.
102

Procedure

A session can be created via the getSession( ) method of HttpServletRequest. An HttpSession object is returned. This object can store a set of bindings that associate names with objects. The

setAttribute( ) getAttribute( ) getAttributeNames( ) removeAttribute( ) methods of HttpSession manage these bindings.

103

DateServlet.java
import import import import java.io.*; java.util.*; javax.servlet.*; javax.servlet.http.*;

When you first request this servlet, the browser displays one line with the current date and time information. On subsequent invocations, two lines are displayed. The first line shows the date and time when the servlet was last accessed. The second line shows the current date and time.

public class DateServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the HttpSession object. HttpSession hs = request.getSession(true); // Get writer. response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.print("<B>"); // Display date/time of last access. Date date = (Date)hs.getAttribute("date"); if(date != null) { pw.print("Last access: " + date + "<br>"); } // Display current date/time. date = new Date(); hs.setAttribute("date", date); pw.println("Current date: " + date); } } C:\j2sdk1.4.2_13\bin\DateServlet.java

104

Explaination of DateServlet.java

The getSession( ) method gets the current session. A new session is created if one does not already exist. The getAttribute( ) method is called to obtain the object that is bound to the name date.

That object is a Date object that encapsulates the date and time when this page was last accessed. (Of course, there is no such binding when the page is first accessed.)
A Date object encapsulating the current date and time is then created. The setAttribute( ) method is called to bind the name date to this object.

105

Vous aimerez peut-être aussi