90
IADCS Diploma Course Java Servlet Programming U Nyein Oo U Nyein Oo COO/Director (IT) Myanma Computer Co., Ltd(MCC)

Programming Server side with Sevlet

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Programming Server side with Sevlet

IADCS Diploma CourseJava Servlet Programming

U Nyein OoU Nyein OoCOO/Director (IT)

Myanma Computer Co., Ltd(MCC)

Page 2: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 2

Road Map Servlet Architecture Overview Servlets in Context

Other options for server side development Advantages of Servlets Introduction to Java Server Pages

(JSP) Servlets v. JSP

Page 3: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 3

What is a Servlet? Java’s answer to the Common Gateway

Interface (CGI). Applet: a java program that runs within

the web browser. Servlet: a java program that runs within

the web server. Rapidly becoming the standard for

building web applications.

Page 4: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 4

Life of a Servlet Regardless of the application, servlets

usually carry out the following routine:1) Read any data sent by the user

Capture data submitted by an HTML form.

2) Look up any HTTP information Determine the browser version, host name of

client, cookies, etc.

3) Generate the Results Connect to databases, connect to legacy

applications, etc.

Page 5: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 5

Life of a Servlet (cont.)

4) Format the Results Generate HTML on the fly

5) Set the Appropriate HTTP headers Tell the browser the type of document

being returned or set any cookies.

6) Send the document back to the client

Page 6: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 6

Life of a Servlet

WebBrowser

WebServer

JavaServlet

Database

1,2

3

4,5 6

Page 7: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 7

What can you build with Servlets?

Search Engines Personalization Systems E-Commerce Applications Shopping Carts Product Catalogs Intranet Applications Groupware Applications: bulletin boards, file

sharing, etc.

Page 8: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 8

Server Side Options There are many options for creating server

side applications. We will examine some of these options

briefly. This better enables us to understand servlets

within the broader context of web development.

Also enables us to better understand the advantages and disadvantages of servlets.

Page 9: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 9

Server Side Options Common Gateway Interface (CGI) Fast CGI Mod Perl ASP PHP Cold Fusion

Page 10: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 10

Common Features All server side frameworks share a

common set of features: Read data submitted by the user Generate HTML dynamically based on

user input Determine information about the client

browser Access Database systems Exploit the HTTP protocol

Page 11: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 11

Decision Points When evaluating which server side framework

to use, you need to consider a number of critical factors: Ease of development:

How easily can you build new applications? Performance:

How fast can the framework respond to queries? Scalability:

Can the framework scale to thousands, millions of users? Security:

Are there any inherent security vulnerabilities?

Page 12: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 12

Option 1: CGI Represents one of the earliest, practical

methods for generating web content. Primarily written in the Perl

programming language. Unfortunately, traditional CGI programs

suffer from scalability and performance problems.

Let’s examine these two problems…

Page 13: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 13

CGI Architecture1) Browser initiates request

2) Web server receives the request.

3) For each request, web server spawns a new operating system process to execute the CGI/Perl Program.

WebBrowser

WebServer

Perl/CGI

CreateNew process

Page 14: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 14

CGI Architecture For each browser request, the web

server must spawn a new operating system process.

Browser 1

WebServer

Perl 1

Browser 2

Browser N

Perl 2

Perl N

Page 15: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 15

CGI Architecture Spawning a new operating system

process for each request takes time and memory.

Hence, traditional CGI programs have inherent performance and scalability problems.

Every other server architecture tries to address these problems.

Page 16: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 16

Option 2: Fast CGI Developed by Open Market as an option for

developing faster, more scalable CGI programs. Fast CGI works by creating a pool of processes for

handling CGI requests. When a CGI request comes in, Fast CGI picks one

of the processes from the pool and assigns it to the task.

Without the overhead of creating new operating system processes, FastCGI is much faster than traditional CGI.

For more information, see http://www.fastcgi.com

Page 17: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 17

Option 3: Mod Perl A module of the Apache Web Server. Embeds the Perl interpreter directly within the

web server. Perl programs are therefore precompiled. Because Perl is embedded within the Server,

Mod Perl does not need to create a new process for each request.

Like FastCGI, Mod Perl is much faster than traditional CGI.

For more information, see: http://perl.apache.org

Page 18: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 18

Option 4: ASP Active Server Pages Runs on Microsoft’s Web Server: Internet

Information Server (IIS) Programmers add ASP code directly into their

HTML pages. When a client requests a page, the Web Server

takes the HTML page, runs the ASP code within the page, and returns a complete HTML page.

Faster than traditional CGI, but only works on Microsoft IIS.

Page 19: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 19

Option 5: Cold Fusion Developed by Allaire Corporation (now owned

by Macromedia.) Provides excellent database access and

database tools. Great platform for rapid prototyping and rapid

development. For more information:

http://www.macromedia.com

Page 20: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 20

Option 6: PHP An open source project written entirely

by volunteers Provides simple, but powerful database

access. Also great for rapid development. For additional information:

http://www.php.net

Page 21: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 21

Advantages of Servlets Servlets have six main advantages:

Efficient Convenient Powerful Portable Secure Inexpensive

Page 22: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 22

Advantage 1: Efficient For each browser request, the servlet

spawns a light weight thread. This is faster and more efficient that

spawning a new operating system process.

Hence, servlets have better performance and better scalability than traditional CGI.

Page 23: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 23

Advantage 2: Convenient Servlets include built-in functionality for:

Reading HTML form data Handling cookies Tracking user sessions Setting HTTP headers

Java is object oriented

Page 24: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 24

Advantage 3: Powerful Servlets can talk directly to the web

servers. Multiple servlets can share data:

Particularly important for maintaining database connections.

Includes powerful techniques for tracking user sessions.

Page 25: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 25

Advantage 4: Portable One of the advantages of Java is its

portability across different operating systems.

Servlets have the same advantages. You can therefore write your servlets on

Windows, then deploy them on UNIX. You can also run any of your servlets on

any Java-enabled web server, with no code changes.

Page 26: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 26

Advantage 5: Secure Traditional CGI programs have a number

of known security vulnerabilities. Hence, you usually need to include a

separate Perl/CGI module to supply the necessary security protection.

Java has a number of built-in security layers.

Hence, servlets are considered more secure than traditional CGI programs.

Page 27: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 27

Advantage 6: Inexpensive You can download free servlet kits for

development use. You can therefore get started for free! Nonetheless, production strength

servlet web servers can get quite expensive.

Page 28: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 28

Java Server Pages Related to Java Servlets Can be used alone or in conjunction

with servlets Represent (yet) another method for

creating server side applications

Page 29: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 29

Servlets v. JSP Servlets

code looks like a regular Java program. JSP

embed Java commands directly within HTML

Let’s examine a Servlet program next to a JSP program…

Each of these prints, “Hello, World!”

Page 30: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 30

Servlet EngineThere are three kinds of Servlet engine

Stand Alone Servlet Engine Add-on Servlet Engine Embedded Servlet Engine

Page 31: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 31

Stand Alone Servlet Engine A standalone servlet engine is a server that

includes built-in support for servlets. Such an engine has the advantage that

everything works right out of the box. O ne disadvantage, however, is that you have

to wait for a new release of the web server to get the latest servlet support.

Page 32: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 32

Add-On Servlet Engine An add-on servlet engine functions as a plug-

in to an existing server--it adds servlet support to a server that was not originally designed with servlets in mind.

Add-on servlet engines have been written for many servers including Apache, Netscape's FastTrack Server and Enterprise Server, Microsoft's Internet Information Server and Personal Web Server, O'Reilly's WebSite, Lotus Domino's Go Webserver, StarNine's WebSTAR, and Apple's AppleShareIP

Page 33: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 33

Embedded Servlet Engine An embeddable engine is generally a

lightweight servlet deployment platform that can be embedded in another application. The application becomes the true server.

Page 34: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 34

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

public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<HTML>"); out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>"); out.println("<BODY>"); out.println("<BIG>Hello World</BIG>"); out.println("</BODY></HTML>"); }}

A Java Servlet :Looks like a regular Java program

Page 35: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 35

<html> <head><title>Hello, World JSP Example</title></head> <body> <h2> Hello, World! The current time in milliseconds is <%= System.currentTimeMillis() %> </h2></body></html>

A JSP Page :Looks like a regular HTML page.

Embedded Javacommand toprint current time.

Page 36: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 36

Servlet Lift Cycle Overview of the Life Cycle Birth of a Servlet Life of a Servlet Threading Issues Death of a Servlet Tips for Debugging Servlets

Page 37: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 37

Life of a Servlet Birth: Create and initialize the servlet

Important method: init() Life: Handle 0 or more client requests

Important methods: service(), doGet(), and doPost().

Death: Destroy the servlet Important method: destroy()

Page 38: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 38

Birth of Servlet

The init() method

The init() method is called when the servlet is first requested by a browser request.

It is not called again for each request. Used for one-time initialization.

Page 39: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 39

Simple Example

The init() method is a good place to put any initialization variables.

For example, the following servlet records its Birth Date/time…

Page 40: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 40

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

public class Birth extends HttpServlet {Date birthDate;

// Init() is called firstpublic void init() throws ServletException {

birthDate = new Date();}

Page 41: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 41

// Handle an HTTP GET Requestpublic void doGet(HttpServletRequest request,

HttpServletResponse response) throws IOException, ServletException {

response.setContentType("text/plain");PrintWriter out = response.getWriter();out.println ("I was born on: "+birthDate);out.close();

}}

Page 42: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 42

Life of a Servlet The first time a servlet is called, the

Servlet is instantiated, and its init() method is called.

Only one instance of the servlet is instantiated.

This one instance handles all browser requests.

Page 43: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 43

Service() Method Each time the server receives a request for a servlet,

the server spawns a new thread and calls the servlet’s service () method.

Browser

Browser

Browser Web Server Single Instanceof Servlet

service()

service()

service()

Page 44: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 44

Let’s Prove it… To prove that only one instance of a servlet is

created, let’s create a simple example. The Counter Servlet keeps track of the number of

times it has been accessed. This example maintains a single instance variable,

called count. Each time the servlet is called, the count variable is

incremented. If the Server created a new instance of the Servlet

for each request, count would always be 0!

Page 45: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 45

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

public class Counter extends HttpServlet {// Create an instance variableint count = 0;

// Handle an HTTP GET Requestpublic void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

response.setContentType("text/plain");PrintWriter out = response.getWriter();count++;out.println ("Since loading, this servlet has "

+ "been accessed "+ count + " times.");out.close();

}}

Only one instance of thecounter Servlet is created.Each browser request istherefore incrementing thesame count variable.

Page 46: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 46

The Service Method By default the service() method checks the

HTTP Header. Based on the header, service calls either

doPost() or doGet(). doPost and doGet is where you put the

majority of your code. If your servlets needs to handle both get and

post identically, have your doPost() method call doGet() or vice versa.

Page 47: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 47

Thread Synchronization By default, multiple threads are accessing the

same servlet object at the same time. You therefore need to be careful to

synchronize access to shared data. For example, the code on the next slide has a

problem…

Page 48: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 48

package coreservlets;

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

public class UserIDs extends HttpServlet { private int nextID = 0; public void doGet(

HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Your ID"; String docType = … String id = "User-ID-" + nextID; out.println("<H2>" + id + "</H2>"); nextID = nextID + 1; out.println("</BODY></HTML>"); }}

This code is problematic. Can result in a race condition, where two users can actuallyget the same User-ID!

For example:

User 1 makes request:

String id = "User-ID-" + nextID; Gets nextId of 45.

Now User 2 makes request,and pre-empts user 1:

String id = "User-ID-" + nextID; Gets nextId of 45 (same one!)

Admittedly, this case is rare,but it’s especially problematic.Imagine if user Id was tied tocredit card number!

Page 49: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 49

How to Solve Synchronization Problems

You have a few options for solving servlet synchronization issues:

1) Never use instance variables in your servlets. If you don’t have shared instance variables, you don’t have shared synchronization problems.

2) Synchronize code explicitly with Java synchronization blocks.

3) Use the SingleThreadInterface (not recommended)

Page 50: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 50

Java Synchronization Use a synchronization block whenever

accessing/modifying a shared variable. For example:

synchronized (this) {String id = "User-ID-" + nextID;out.println("<H2>" + id + "</H2>");nextID = nextID + 1;

}

Page 51: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 51

SingleThreadModel Interface To prevent multi-threaded access, you can have your servlet

implement the SingleThreadModel:public class YourServlet extends HttpServlet implements

SingleThreadModel {…

} This will guarantee that your servlet will only process one browser

request at a time. It therefore addresses most synchronization issues. Unfortunately, however, it can result in severe slowing of

performance, and most people strongly recommend against using it.

In fact, the SingleThreadModel interface is now deprecated in the Servlet 2.4 API.

Page 52: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 52

Death of a Servlet Before a server shuts down, it will call

the servlet’s destroy() method. You can handle any servlet clean up

here. For example: Updating log files. Closing database connections. Closing any socket connections.

Page 53: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 53

Example: Death.java This next example illustrates the use of

the destroy() method. While alive, the servlet will say “I am

alive!”. When the server is stopped, the

destroy() method is called, and the servlet records its time of death in a “rip.txt” text file.

Page 54: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 54

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

public class Death extends HttpServlet {

// Handle an HTTP GET Request public void doGet(HttpServletRequest request, HttpServletResponse

response) throws IOException, ServletException {

response.setContentType("text/plain");PrintWriter out = response.getWriter();out.println ("I am alive!");out.close();

}

Continued….

Page 55: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 55

// This method is called when one stops// the Java Web Server public void destroy() {

try {FileWriter fileWriter = new FileWriter ("rip.txt");Date now = new Date();String rip = "I was destroyed at: "+now.toString();fileWriter.write (rip);fileWriter.close();

} catch (IOException e) {e.printStackTrace();

} }}

Page 56: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 56

A Persistent Counter Now that we know all about the birth, life and

death of a servlet, let’s put this knowledge together to create a persistent counter.

The Counter.java example we covered earlier has a big problem: When you restart the web server, counting starts

all over at 0. It does not retain any persistent memory.

Page 57: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 57

Persistent Counter To create a persistent record, we can

store the count value within a “counter.txt” file. init(): Upon start-up, read in the current

counter value from counter.txt. destroy(): Upon destruction, write out the

new counter value to counter.txt

Page 58: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 58

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

public class CounterPersist extends HttpServlet { String fileName = "counter.txt"; int count;

public void init () {try { FileReader fileReader = new FileReader (fileName); BufferedReader bufferedReader = new BufferedReader (fileReader); String initial = bufferedReader.readLine(); count = Integer.parseInt (initial);} catch (FileNotFoundException e) { count = 0; }

catch (IOException e) { count = 0; } catch (NumberFormatException e) { count = 0; }

}

At Start-up, load the counter from file.In the event of any exception, initializecount to 0.

Continued….

Page 59: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 59

// Handle an HTTP GET Request public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

response.setContentType("text/plain");PrintWriter out = response.getWriter();count++;out.println ("Since loading, this servlet has "

+"been accessed "+ count + " times.");out.close();

} Each time the doGet() method is called, increment the count variable.

Continued….

Page 60: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 60

// At Shutdown, store counter back to file public void destroy() {

try {FileWriter fileWriter = new FileWriter (fileName);String countStr = Integer.toString (count);fileWriter.write (countStr);fileWriter.close();

} catch (IOException e) {e.printStackTrace();

} }}

When destroy() is called, store new counter variable back to counter.txt.

Any problems with this code?

Page 61: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 61

Tips for Debugging Servlets Section 3.8 of our Text has a few tips for

Servlet Debugging. Pay close attention! At this stage, the best debugging option is to

use print statements. print statements will be output to the Tomcat

console (very useful!) Let’s try it out… For production systems, a real logging library,

such as Log4J, is a much better option.

Page 62: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 62

Servlet Cookie API

Creating Cookies Cookie Attributes Reading Cookies Example 1: Basic Counter Example 2: Tracking Multiple Cookies

Page 63: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 63

Creating Cookies Three steps to creating a new cookie:

1) Create a new Cookie Object Cookie cookie = new Cookie (name, value);

2) Set any cookie attributes Cookie.setMaxAge (60);

3) Add your cookie to the response object: Response.addCookie (cookie)

We will examine each of these steps in detail.

Page 64: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 64

1. Cookie Constructor You create a new cookie by calling the

Cookie constructor and specifying: Name Value

Example: Cookie cookie = new Cookie (“school”, “NYU”);

Neither the name nor the value should contain whitespace or any of the following characters: [ ] ( ) = , “ / ? @ ;

Page 65: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 65

2. Set Cookie Attributes Before adding your cookie to the Response

object, you can set any of its attributes. Attributes include:

Name/Value Domain Maximum Age Path Version

Page 66: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 66

Cookie Name

You rarely call setName() directly, as you specify the name in the cookie constructor.

getName() is useful for reading in cookies.

public String getName();

public void setName (String name);

Page 67: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 67

Cookie Value

You rarely call setValue() directly, as you specify the name in the cookie constructor.

getValue() is useful for reading in cookies.

public String getValue();

public void setValue (String value);

Page 68: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 68

Domain Attributes

public String getDomain ();

public void setDomain(String domain);

Normally, the browser only returns cookies to the exact same host that sent them.

You can use setDomain() to instruct the browser to send cookies to other hosts within the same domain.

Page 69: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 69

Domain Example Example: Cookies sent from a servlet at

bali.vacations.com would not be forwarded to mexico.vacations.com.

If you do want to the cookie to be accessible to both hosts, set the domain to the highest level: cookie.setDomain (“.vacations.com”);

Note that you are always required to include at least two dots. Hence, you must specify .vacations.com, not just vacations.com

Page 70: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 70

Cookie Age

In general there are two types of cookies: Session Cookies: Temporary cookies that expire

when the user exits the browser. Persistent Cookies: Cookies that do not expire

when the user exits the browser. These cookies stay around until their expiration date, or the user explicitly deletes them.

public int getMaxAge ();

public void setMaxAge (int lifetime);

Page 71: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 71

Cookie Expiration The setMaxAge () method tells the browser

how long (in seconds) until the cookie expires.

Possible values: Negative Value (default): creates a session

cookie that is deleted when the user exits the browser.

0: instructs the browser to delete the cookie. Positive value: any number of seconds. For

example, to create a cookie that lasts for one hour, setMaxAge (3600);

Page 72: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 72

Path

By default, the browser will only return a cookie to URLs in or below the directory that created the cookie.

public String getPath();

public void setPath (String path);

Page 73: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 73

Path Example Example: If you create a cookie at

http://ecommerce.site.com/toys.html then: The browser will send the cookie back to

http://ecommerce.site.com/toys/bikes.html. The browser will not send the cookie back to

http://ecommerce.site.com/cds If you want the cookie to be sent to all pages,

set the path to / Cookie.setPath (“/”); Very common, widely used practice.

Page 74: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 74

Cookie Version

By default, the Servlet API will create Version 0 cookies.

Via the setVersion() method you can specify version 1. But, since this is not widely implemented, stick with the default.

public int getVersion ();

public void setVersion (int version);

Page 75: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 75

Security

If you set Secure to true, the browser will only return the cookie when connecting over an encrypted connection. (More on SSL later in the semester.)

By default, cookies are set to non-secure.

public int getSecure ();

public void setSecure (boolean);

Page 76: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 76

Comments

Comments: you can specify a cookie comment via the setComment() method. But, comments are only supported in Version 1 cookies.

Hence, no one really uses these methods…

public int getComment ();

public void Comment (String)

Page 77: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 77

3. Add Cookies to Response Once you have created your cookie, and set

any attributes, you add it to the response object.

By adding it to the response object, your cookie is transmitted back to the browser.

Example:Cookie school = new Cookie (“school”, “NYU”);school.setMaxAge (3600);response.addCookie (school);

Page 78: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 78

Reading Cookies To create cookies, add them to the response

object. To read incoming cookies, get them from the

request object. HttpServletRequest has a getCookies()

method. Returns an array of cookie objects. This includes

all cookies sent by the browser. Returns a zero-length array if there are no

cookies.

Page 79: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 79

Reading Cookies Once you have an array of cookies, you

can iterate through the array and extract the one(s) you want.

Our next few examples illustrate how this is done.

Page 80: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 80

Example I: Cookie Counter A few weeks back, we created a simple

Counter servlet that keeps track of the number of “hits”.

Now, we want to display the number of hits for each user.

This is relatively simple to do. We just create a counter cookie, and increment the counter cookie at each visit.

Page 81: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 81

The Code1. Get the array of cookie objects from the

request object.2. Iterate through the array, looking for a

“counter” cookie.3. If the “counter” cookie exists, extract its

value. Otherwise, set the counter to 0.4. Increment the counter by 1.5. Create a new “counter” cookie, and add it to

the response object.

Page 82: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 82

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

public class CookieCounter extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

String name, value = null; Cookie cookie; int counter; res.setContentType("text/html");

// Try to extract the counter cookie (if one exists)Cookie[] cookies = req.getCookies();for (int i=0; i<cookies.length; i++) {

cookie = cookies[i];name = cookie.getName();if (name.equals("counter"))

value = cookie.getValue();}

Page 83: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 83

// If possible, parse the counter value // Otherwise, start over at 0. if (value != null) counter = Integer.parseInt (value); else counter = 0;

// Increment the counter counter++;

// Create a new counter cookie // Cookie will exist for one year cookie = new Cookie ("counter", Integer.toString(counter)); cookie.setMaxAge (60*60*24*365); res.addCookie (cookie);

// Output number of visits PrintWriter out = res.getWriter(); out.println ("<HTML><BODY>"); out.println ("<H1>Number of visits: "+counter); out.println ("</H1>"); out.println ("</BODY></HTML>"); out.close(); }}

Page 84: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 84

HTTP Tracer Before we move on to the next

example, let’s see our code in action via the HTTP Tracer….

Page 85: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 85

Example II: Creating/Reading Multiple Cookies

Example 2 consists of two servlets: SetCookies.java: Creates six independent

cookies. ShowCookies.java: Reads in and displays

any and all cookies. Let’s examine setCookies.java first.

Page 86: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 86

SetCookies.java SetCookies.java creates six unique cookies:

Three Session Cookies Session-Cookie 1, 2, 3 These last until the user exits the browser.

Three Persistent Cookies Persistent-Cookie 1, 2, 3 These last for one year. (slightly different

than the example in the book, which sets it to one hour.)

Page 87: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 87

for(int i=0; i<3; i++) { // Default maxAge is -1, indicating cookie // applies only to current browsing session. Cookie cookie = new Cookie("Session-Cookie-" + i, "Cookie-Value-S" + i); response.addCookie(cookie); cookie = new Cookie("Persistent-Cookie-" + i, "Cookie-Value-P" + i); // Cookie is valid for a year, regardless of whether // user quits browser, reboots computer, or whatever. cookie.setMaxAge (60*60*24*365); response.addCookie(cookie); }

Code Fragment

Page 88: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 88

ShowCookies.java This servlet displays any and all cookies

that sent to it. It does this by first requesting the cookie

array via request.getCookies(); The code then iterates through the array

to display each unique cookie.

Page 89: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 89

Code FragmentCookie[ ] cookies = request.getCookies();if (cookies != null) {

Cookie cookie;for(int i=0; i<cookies.length; i++) {

cookie = cookies[i];out.println("<TR>\n" +

" <TD>" + cookie.getName() + "\n" +" <TD>" + cookie.getValue());

}}

Page 90: Programming Server side with Sevlet

Copyright : MCC Java Servlet Programming 90

Thank You!