cookies. cookie a cookie is a piece of textual information send by the web server to the client...

33
Cookies

Upload: tyler-bryant

Post on 13-Dec-2015

218 views

Category:

Documents


0 download

TRANSCRIPT

Cookies

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

A cookie is a keyed piece of data that is created by the server and stored by the client browser

Browsers maintain their own list of unique cookies This makes cookies a very viable solution for session

The Servlet API provides built-in support for cookies It does this through the use of the Cookie class and the HttpServletResponseaddCookie() and HttpServletRequest getCookies() methods

Cont The problem is privacy not security

bull Dont put sensitive info in cookies

Cookie definition

ndash Web server sends a cookie name and value to a browser and later can read them back from the browser

The process

ndash Servlet sends a cookie with its response to the client

ndash The client saves the cookie

ndash The client returns a cookie back with subsequent requests (depends on some rules)

Servlet API supports cookies

ndash javaxservlethttpcookieResponseaddCookie(Cookie) add cookies to a Response

Cookie cookie = new Cookie(name value)

responseaddCookie(cookie)

reuqestgetCookie() get cookie from a requestCookie[] cookie =requestgetCookie()

if (cookie = null)

for (int i= 0 ilt cookielength i++)

String name = cookie[i]getName()

String value = cookie[i]getValue()

Sending Cookies to the ClientCreate a Cookie object

ndash Call the Cookie constructor with a cookie name and a

cookie value both of which are strings

Cookie c = new Cookie(userID a1234)

bull Set the maximum age

ndash To tell browser to store cookie on disk instead of just in

memory use setMaxAge (argument is in seconds)

csetMaxAge(6060247) One week

bull Place the Cookie into the HTTP response

ndash Use responseaddCookie

ndash If you forget this step no cookie is sent to the browser

responseaddCookie(c)

Reading Cookies from the Client Call requestgetCookies ndash This yields an array of Cookie objects bull Loop down the array calling getName on each

entry until you find the cookie of interest ndash Use the value (getValue) in application-specific way

String cookieName = userID

Cookie[] cookies = requestgetCookies()

if (cookies = null)

for(int i=0 iltcookieslength i++)

Cookie cookie = cookies[i]

if (cookieNameequals(cookiegetName()))

doSomethingWith(cookiegetValue())

Using Cookie MethodsgetDomainsetDomain

ndash Lets you specify domain to which cookie applies Current

host must be part of domain specified

bull getMaxAgesetMaxAge

ndash Getssets the cookie expiration time (in seconds) If you

fail to set this cookie applies to current browsing session

only See LongLivedCookie helper class given earlier

bull getName

ndash Gets the cookie name There is no setName method you

supply name to constructor For incoming cookie array

you use getName to find the cookie of interest

getPathsetPath

ndash Getssets the path to which cookie applies If unspecified

cookie applies to URLs that are within or below directory containing current page

bull getSecuresetSecure

ndash Getssets flag indicating whether cookie should apply

only to SSL connections or to all connections

bull getValuesetValue

ndash Getssets value associated with cookie For new cookies

you supply value to constructor not to setValue For

incoming cookie array you use getName to find the

cookie of interest then call getValue on the result If you

set the value of an incoming cookie you still have to send

it back out with responseaddCookie

Advantages

ndash Very easy to implement

ndash Highly customizable

ndash Persist across browser shut-downs

Disadvantages

ndash Often users turn off cookies for privacy

or security reason

ndash Not quite universal browser support

Add Cookiehtml

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=post

action=httplocalhost8080examplesservletsservletAddCookieServletgt

ltBgtEnter a value for MyCookieltBgt

ltinput type=textbox name=data size=25 value=gt

ltinput type=submit value=Submitgt

ltformgt

ltbodygt

lthtmlgt

AddCookie Serveletjava

import javaio

import javaxservlet

import javaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

pwclose()

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=postldquo action=httplocalhost8080examplesservletsservletPostParametersServletgt

lttablegt

lttrgt

lttdgtltBgtEmployeelttdgt

lttdgtltinput type=textbox name=e size=25 value=gtlttdgt

lttrgt

lttrgt

lttdgtltBgtPhonelttdgt

lttdgtltinput type=textbox name=p size=25 value=gtlttdgt

lttrgt

lttablegt

ltinput type=submit value=Submitgt

ltbodygt

lthtmlgt

import javaioimport javaxservletimport javaxservlethttp public class CookieExample extends HttpServlet public void doGet(HttpServletRequest request HttpServletResponse response) throws IOException ServletException responsesetContentType(texthtml) PrintWriter out = responsegetWriter() print out cookies Cookie[] cookies = requestgetCookies() for (int i = 0 i lt cookieslength i++) Cookie c = cookies[i] String name = cgetName() String value = cgetValue() outprintln(name + = + value)

set a cookie

String name = requestgetParameter(cookieName)

if (name = null ampamp namelength() gt 0)

String value = requestgetParameter(cookieValue)

Cookie c = new Cookie(name value)

responseaddCookie(c)

Webxml

ltservletgt

ltservlet-namegtCookieExampleltservlet-namegt

ltservlet-classgtCookieExampleltservlet-classgt

ltservletgt

ltservlet-mappinggt

ltservlet-namegtCookieExampleltservlet-namegt lturl-patterngtservletsservletCookieExamplelturl-patterngt

ltservlet-mappinggt

Cookies Example

Your browser is sending the following cookiesCookie Name venkatCookie Value 90Create a cookie to send to your browserName Value

Submit Query

Venkta

Venkat

How Do We Need HTTP StateWeb applications need to track the users

across a series of requests

Online shopping (eg Order books)

ndash Financial portfolio manager

ndash Movie listings HTTP does not support directly Need a mechanism to maintain state about a series of requests

from the same user ( or originating from the same browser) over some period of time

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

Number of problems that arise from the fact that HTTP is a stateless protocol In particular when you are doing on-line shopping it is a real annoyance that the Web server cant easily remember previous transactions

This makes applications like shopping carts very problematic when you add an entry to your cart how does the server know whats already in your cart Even if servers did retain contextual information youd still have problems with e-commerce how does the server remember what you were buying

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( ) and removeAttribute( ) methods of HttpSession manage these

bindings

It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

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

A cookie is a keyed piece of data that is created by the server and stored by the client browser

Browsers maintain their own list of unique cookies This makes cookies a very viable solution for session

The Servlet API provides built-in support for cookies It does this through the use of the Cookie class and the HttpServletResponseaddCookie() and HttpServletRequest getCookies() methods

Cont The problem is privacy not security

bull Dont put sensitive info in cookies

Cookie definition

ndash Web server sends a cookie name and value to a browser and later can read them back from the browser

The process

ndash Servlet sends a cookie with its response to the client

ndash The client saves the cookie

ndash The client returns a cookie back with subsequent requests (depends on some rules)

Servlet API supports cookies

ndash javaxservlethttpcookieResponseaddCookie(Cookie) add cookies to a Response

Cookie cookie = new Cookie(name value)

responseaddCookie(cookie)

reuqestgetCookie() get cookie from a requestCookie[] cookie =requestgetCookie()

if (cookie = null)

for (int i= 0 ilt cookielength i++)

String name = cookie[i]getName()

String value = cookie[i]getValue()

Sending Cookies to the ClientCreate a Cookie object

ndash Call the Cookie constructor with a cookie name and a

cookie value both of which are strings

Cookie c = new Cookie(userID a1234)

bull Set the maximum age

ndash To tell browser to store cookie on disk instead of just in

memory use setMaxAge (argument is in seconds)

csetMaxAge(6060247) One week

bull Place the Cookie into the HTTP response

ndash Use responseaddCookie

ndash If you forget this step no cookie is sent to the browser

responseaddCookie(c)

Reading Cookies from the Client Call requestgetCookies ndash This yields an array of Cookie objects bull Loop down the array calling getName on each

entry until you find the cookie of interest ndash Use the value (getValue) in application-specific way

String cookieName = userID

Cookie[] cookies = requestgetCookies()

if (cookies = null)

for(int i=0 iltcookieslength i++)

Cookie cookie = cookies[i]

if (cookieNameequals(cookiegetName()))

doSomethingWith(cookiegetValue())

Using Cookie MethodsgetDomainsetDomain

ndash Lets you specify domain to which cookie applies Current

host must be part of domain specified

bull getMaxAgesetMaxAge

ndash Getssets the cookie expiration time (in seconds) If you

fail to set this cookie applies to current browsing session

only See LongLivedCookie helper class given earlier

bull getName

ndash Gets the cookie name There is no setName method you

supply name to constructor For incoming cookie array

you use getName to find the cookie of interest

getPathsetPath

ndash Getssets the path to which cookie applies If unspecified

cookie applies to URLs that are within or below directory containing current page

bull getSecuresetSecure

ndash Getssets flag indicating whether cookie should apply

only to SSL connections or to all connections

bull getValuesetValue

ndash Getssets value associated with cookie For new cookies

you supply value to constructor not to setValue For

incoming cookie array you use getName to find the

cookie of interest then call getValue on the result If you

set the value of an incoming cookie you still have to send

it back out with responseaddCookie

Advantages

ndash Very easy to implement

ndash Highly customizable

ndash Persist across browser shut-downs

Disadvantages

ndash Often users turn off cookies for privacy

or security reason

ndash Not quite universal browser support

Add Cookiehtml

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=post

action=httplocalhost8080examplesservletsservletAddCookieServletgt

ltBgtEnter a value for MyCookieltBgt

ltinput type=textbox name=data size=25 value=gt

ltinput type=submit value=Submitgt

ltformgt

ltbodygt

lthtmlgt

AddCookie Serveletjava

import javaio

import javaxservlet

import javaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

pwclose()

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=postldquo action=httplocalhost8080examplesservletsservletPostParametersServletgt

lttablegt

lttrgt

lttdgtltBgtEmployeelttdgt

lttdgtltinput type=textbox name=e size=25 value=gtlttdgt

lttrgt

lttrgt

lttdgtltBgtPhonelttdgt

lttdgtltinput type=textbox name=p size=25 value=gtlttdgt

lttrgt

lttablegt

ltinput type=submit value=Submitgt

ltbodygt

lthtmlgt

import javaioimport javaxservletimport javaxservlethttp public class CookieExample extends HttpServlet public void doGet(HttpServletRequest request HttpServletResponse response) throws IOException ServletException responsesetContentType(texthtml) PrintWriter out = responsegetWriter() print out cookies Cookie[] cookies = requestgetCookies() for (int i = 0 i lt cookieslength i++) Cookie c = cookies[i] String name = cgetName() String value = cgetValue() outprintln(name + = + value)

set a cookie

String name = requestgetParameter(cookieName)

if (name = null ampamp namelength() gt 0)

String value = requestgetParameter(cookieValue)

Cookie c = new Cookie(name value)

responseaddCookie(c)

Webxml

ltservletgt

ltservlet-namegtCookieExampleltservlet-namegt

ltservlet-classgtCookieExampleltservlet-classgt

ltservletgt

ltservlet-mappinggt

ltservlet-namegtCookieExampleltservlet-namegt lturl-patterngtservletsservletCookieExamplelturl-patterngt

ltservlet-mappinggt

Cookies Example

Your browser is sending the following cookiesCookie Name venkatCookie Value 90Create a cookie to send to your browserName Value

Submit Query

Venkta

Venkat

How Do We Need HTTP StateWeb applications need to track the users

across a series of requests

Online shopping (eg Order books)

ndash Financial portfolio manager

ndash Movie listings HTTP does not support directly Need a mechanism to maintain state about a series of requests

from the same user ( or originating from the same browser) over some period of time

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

Number of problems that arise from the fact that HTTP is a stateless protocol In particular when you are doing on-line shopping it is a real annoyance that the Web server cant easily remember previous transactions

This makes applications like shopping carts very problematic when you add an entry to your cart how does the server know whats already in your cart Even if servers did retain contextual information youd still have problems with e-commerce how does the server remember what you were buying

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( ) and removeAttribute( ) methods of HttpSession manage these

bindings

It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

Cont The problem is privacy not security

bull Dont put sensitive info in cookies

Cookie definition

ndash Web server sends a cookie name and value to a browser and later can read them back from the browser

The process

ndash Servlet sends a cookie with its response to the client

ndash The client saves the cookie

ndash The client returns a cookie back with subsequent requests (depends on some rules)

Servlet API supports cookies

ndash javaxservlethttpcookieResponseaddCookie(Cookie) add cookies to a Response

Cookie cookie = new Cookie(name value)

responseaddCookie(cookie)

reuqestgetCookie() get cookie from a requestCookie[] cookie =requestgetCookie()

if (cookie = null)

for (int i= 0 ilt cookielength i++)

String name = cookie[i]getName()

String value = cookie[i]getValue()

Sending Cookies to the ClientCreate a Cookie object

ndash Call the Cookie constructor with a cookie name and a

cookie value both of which are strings

Cookie c = new Cookie(userID a1234)

bull Set the maximum age

ndash To tell browser to store cookie on disk instead of just in

memory use setMaxAge (argument is in seconds)

csetMaxAge(6060247) One week

bull Place the Cookie into the HTTP response

ndash Use responseaddCookie

ndash If you forget this step no cookie is sent to the browser

responseaddCookie(c)

Reading Cookies from the Client Call requestgetCookies ndash This yields an array of Cookie objects bull Loop down the array calling getName on each

entry until you find the cookie of interest ndash Use the value (getValue) in application-specific way

String cookieName = userID

Cookie[] cookies = requestgetCookies()

if (cookies = null)

for(int i=0 iltcookieslength i++)

Cookie cookie = cookies[i]

if (cookieNameequals(cookiegetName()))

doSomethingWith(cookiegetValue())

Using Cookie MethodsgetDomainsetDomain

ndash Lets you specify domain to which cookie applies Current

host must be part of domain specified

bull getMaxAgesetMaxAge

ndash Getssets the cookie expiration time (in seconds) If you

fail to set this cookie applies to current browsing session

only See LongLivedCookie helper class given earlier

bull getName

ndash Gets the cookie name There is no setName method you

supply name to constructor For incoming cookie array

you use getName to find the cookie of interest

getPathsetPath

ndash Getssets the path to which cookie applies If unspecified

cookie applies to URLs that are within or below directory containing current page

bull getSecuresetSecure

ndash Getssets flag indicating whether cookie should apply

only to SSL connections or to all connections

bull getValuesetValue

ndash Getssets value associated with cookie For new cookies

you supply value to constructor not to setValue For

incoming cookie array you use getName to find the

cookie of interest then call getValue on the result If you

set the value of an incoming cookie you still have to send

it back out with responseaddCookie

Advantages

ndash Very easy to implement

ndash Highly customizable

ndash Persist across browser shut-downs

Disadvantages

ndash Often users turn off cookies for privacy

or security reason

ndash Not quite universal browser support

Add Cookiehtml

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=post

action=httplocalhost8080examplesservletsservletAddCookieServletgt

ltBgtEnter a value for MyCookieltBgt

ltinput type=textbox name=data size=25 value=gt

ltinput type=submit value=Submitgt

ltformgt

ltbodygt

lthtmlgt

AddCookie Serveletjava

import javaio

import javaxservlet

import javaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

pwclose()

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=postldquo action=httplocalhost8080examplesservletsservletPostParametersServletgt

lttablegt

lttrgt

lttdgtltBgtEmployeelttdgt

lttdgtltinput type=textbox name=e size=25 value=gtlttdgt

lttrgt

lttrgt

lttdgtltBgtPhonelttdgt

lttdgtltinput type=textbox name=p size=25 value=gtlttdgt

lttrgt

lttablegt

ltinput type=submit value=Submitgt

ltbodygt

lthtmlgt

import javaioimport javaxservletimport javaxservlethttp public class CookieExample extends HttpServlet public void doGet(HttpServletRequest request HttpServletResponse response) throws IOException ServletException responsesetContentType(texthtml) PrintWriter out = responsegetWriter() print out cookies Cookie[] cookies = requestgetCookies() for (int i = 0 i lt cookieslength i++) Cookie c = cookies[i] String name = cgetName() String value = cgetValue() outprintln(name + = + value)

set a cookie

String name = requestgetParameter(cookieName)

if (name = null ampamp namelength() gt 0)

String value = requestgetParameter(cookieValue)

Cookie c = new Cookie(name value)

responseaddCookie(c)

Webxml

ltservletgt

ltservlet-namegtCookieExampleltservlet-namegt

ltservlet-classgtCookieExampleltservlet-classgt

ltservletgt

ltservlet-mappinggt

ltservlet-namegtCookieExampleltservlet-namegt lturl-patterngtservletsservletCookieExamplelturl-patterngt

ltservlet-mappinggt

Cookies Example

Your browser is sending the following cookiesCookie Name venkatCookie Value 90Create a cookie to send to your browserName Value

Submit Query

Venkta

Venkat

How Do We Need HTTP StateWeb applications need to track the users

across a series of requests

Online shopping (eg Order books)

ndash Financial portfolio manager

ndash Movie listings HTTP does not support directly Need a mechanism to maintain state about a series of requests

from the same user ( or originating from the same browser) over some period of time

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

Number of problems that arise from the fact that HTTP is a stateless protocol In particular when you are doing on-line shopping it is a real annoyance that the Web server cant easily remember previous transactions

This makes applications like shopping carts very problematic when you add an entry to your cart how does the server know whats already in your cart Even if servers did retain contextual information youd still have problems with e-commerce how does the server remember what you were buying

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( ) and removeAttribute( ) methods of HttpSession manage these

bindings

It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

Servlet API supports cookies

ndash javaxservlethttpcookieResponseaddCookie(Cookie) add cookies to a Response

Cookie cookie = new Cookie(name value)

responseaddCookie(cookie)

reuqestgetCookie() get cookie from a requestCookie[] cookie =requestgetCookie()

if (cookie = null)

for (int i= 0 ilt cookielength i++)

String name = cookie[i]getName()

String value = cookie[i]getValue()

Sending Cookies to the ClientCreate a Cookie object

ndash Call the Cookie constructor with a cookie name and a

cookie value both of which are strings

Cookie c = new Cookie(userID a1234)

bull Set the maximum age

ndash To tell browser to store cookie on disk instead of just in

memory use setMaxAge (argument is in seconds)

csetMaxAge(6060247) One week

bull Place the Cookie into the HTTP response

ndash Use responseaddCookie

ndash If you forget this step no cookie is sent to the browser

responseaddCookie(c)

Reading Cookies from the Client Call requestgetCookies ndash This yields an array of Cookie objects bull Loop down the array calling getName on each

entry until you find the cookie of interest ndash Use the value (getValue) in application-specific way

String cookieName = userID

Cookie[] cookies = requestgetCookies()

if (cookies = null)

for(int i=0 iltcookieslength i++)

Cookie cookie = cookies[i]

if (cookieNameequals(cookiegetName()))

doSomethingWith(cookiegetValue())

Using Cookie MethodsgetDomainsetDomain

ndash Lets you specify domain to which cookie applies Current

host must be part of domain specified

bull getMaxAgesetMaxAge

ndash Getssets the cookie expiration time (in seconds) If you

fail to set this cookie applies to current browsing session

only See LongLivedCookie helper class given earlier

bull getName

ndash Gets the cookie name There is no setName method you

supply name to constructor For incoming cookie array

you use getName to find the cookie of interest

getPathsetPath

ndash Getssets the path to which cookie applies If unspecified

cookie applies to URLs that are within or below directory containing current page

bull getSecuresetSecure

ndash Getssets flag indicating whether cookie should apply

only to SSL connections or to all connections

bull getValuesetValue

ndash Getssets value associated with cookie For new cookies

you supply value to constructor not to setValue For

incoming cookie array you use getName to find the

cookie of interest then call getValue on the result If you

set the value of an incoming cookie you still have to send

it back out with responseaddCookie

Advantages

ndash Very easy to implement

ndash Highly customizable

ndash Persist across browser shut-downs

Disadvantages

ndash Often users turn off cookies for privacy

or security reason

ndash Not quite universal browser support

Add Cookiehtml

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=post

action=httplocalhost8080examplesservletsservletAddCookieServletgt

ltBgtEnter a value for MyCookieltBgt

ltinput type=textbox name=data size=25 value=gt

ltinput type=submit value=Submitgt

ltformgt

ltbodygt

lthtmlgt

AddCookie Serveletjava

import javaio

import javaxservlet

import javaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

pwclose()

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=postldquo action=httplocalhost8080examplesservletsservletPostParametersServletgt

lttablegt

lttrgt

lttdgtltBgtEmployeelttdgt

lttdgtltinput type=textbox name=e size=25 value=gtlttdgt

lttrgt

lttrgt

lttdgtltBgtPhonelttdgt

lttdgtltinput type=textbox name=p size=25 value=gtlttdgt

lttrgt

lttablegt

ltinput type=submit value=Submitgt

ltbodygt

lthtmlgt

import javaioimport javaxservletimport javaxservlethttp public class CookieExample extends HttpServlet public void doGet(HttpServletRequest request HttpServletResponse response) throws IOException ServletException responsesetContentType(texthtml) PrintWriter out = responsegetWriter() print out cookies Cookie[] cookies = requestgetCookies() for (int i = 0 i lt cookieslength i++) Cookie c = cookies[i] String name = cgetName() String value = cgetValue() outprintln(name + = + value)

set a cookie

String name = requestgetParameter(cookieName)

if (name = null ampamp namelength() gt 0)

String value = requestgetParameter(cookieValue)

Cookie c = new Cookie(name value)

responseaddCookie(c)

Webxml

ltservletgt

ltservlet-namegtCookieExampleltservlet-namegt

ltservlet-classgtCookieExampleltservlet-classgt

ltservletgt

ltservlet-mappinggt

ltservlet-namegtCookieExampleltservlet-namegt lturl-patterngtservletsservletCookieExamplelturl-patterngt

ltservlet-mappinggt

Cookies Example

Your browser is sending the following cookiesCookie Name venkatCookie Value 90Create a cookie to send to your browserName Value

Submit Query

Venkta

Venkat

How Do We Need HTTP StateWeb applications need to track the users

across a series of requests

Online shopping (eg Order books)

ndash Financial portfolio manager

ndash Movie listings HTTP does not support directly Need a mechanism to maintain state about a series of requests

from the same user ( or originating from the same browser) over some period of time

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

Number of problems that arise from the fact that HTTP is a stateless protocol In particular when you are doing on-line shopping it is a real annoyance that the Web server cant easily remember previous transactions

This makes applications like shopping carts very problematic when you add an entry to your cart how does the server know whats already in your cart Even if servers did retain contextual information youd still have problems with e-commerce how does the server remember what you were buying

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( ) and removeAttribute( ) methods of HttpSession manage these

bindings

It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

Sending Cookies to the ClientCreate a Cookie object

ndash Call the Cookie constructor with a cookie name and a

cookie value both of which are strings

Cookie c = new Cookie(userID a1234)

bull Set the maximum age

ndash To tell browser to store cookie on disk instead of just in

memory use setMaxAge (argument is in seconds)

csetMaxAge(6060247) One week

bull Place the Cookie into the HTTP response

ndash Use responseaddCookie

ndash If you forget this step no cookie is sent to the browser

responseaddCookie(c)

Reading Cookies from the Client Call requestgetCookies ndash This yields an array of Cookie objects bull Loop down the array calling getName on each

entry until you find the cookie of interest ndash Use the value (getValue) in application-specific way

String cookieName = userID

Cookie[] cookies = requestgetCookies()

if (cookies = null)

for(int i=0 iltcookieslength i++)

Cookie cookie = cookies[i]

if (cookieNameequals(cookiegetName()))

doSomethingWith(cookiegetValue())

Using Cookie MethodsgetDomainsetDomain

ndash Lets you specify domain to which cookie applies Current

host must be part of domain specified

bull getMaxAgesetMaxAge

ndash Getssets the cookie expiration time (in seconds) If you

fail to set this cookie applies to current browsing session

only See LongLivedCookie helper class given earlier

bull getName

ndash Gets the cookie name There is no setName method you

supply name to constructor For incoming cookie array

you use getName to find the cookie of interest

getPathsetPath

ndash Getssets the path to which cookie applies If unspecified

cookie applies to URLs that are within or below directory containing current page

bull getSecuresetSecure

ndash Getssets flag indicating whether cookie should apply

only to SSL connections or to all connections

bull getValuesetValue

ndash Getssets value associated with cookie For new cookies

you supply value to constructor not to setValue For

incoming cookie array you use getName to find the

cookie of interest then call getValue on the result If you

set the value of an incoming cookie you still have to send

it back out with responseaddCookie

Advantages

ndash Very easy to implement

ndash Highly customizable

ndash Persist across browser shut-downs

Disadvantages

ndash Often users turn off cookies for privacy

or security reason

ndash Not quite universal browser support

Add Cookiehtml

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=post

action=httplocalhost8080examplesservletsservletAddCookieServletgt

ltBgtEnter a value for MyCookieltBgt

ltinput type=textbox name=data size=25 value=gt

ltinput type=submit value=Submitgt

ltformgt

ltbodygt

lthtmlgt

AddCookie Serveletjava

import javaio

import javaxservlet

import javaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

pwclose()

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=postldquo action=httplocalhost8080examplesservletsservletPostParametersServletgt

lttablegt

lttrgt

lttdgtltBgtEmployeelttdgt

lttdgtltinput type=textbox name=e size=25 value=gtlttdgt

lttrgt

lttrgt

lttdgtltBgtPhonelttdgt

lttdgtltinput type=textbox name=p size=25 value=gtlttdgt

lttrgt

lttablegt

ltinput type=submit value=Submitgt

ltbodygt

lthtmlgt

import javaioimport javaxservletimport javaxservlethttp public class CookieExample extends HttpServlet public void doGet(HttpServletRequest request HttpServletResponse response) throws IOException ServletException responsesetContentType(texthtml) PrintWriter out = responsegetWriter() print out cookies Cookie[] cookies = requestgetCookies() for (int i = 0 i lt cookieslength i++) Cookie c = cookies[i] String name = cgetName() String value = cgetValue() outprintln(name + = + value)

set a cookie

String name = requestgetParameter(cookieName)

if (name = null ampamp namelength() gt 0)

String value = requestgetParameter(cookieValue)

Cookie c = new Cookie(name value)

responseaddCookie(c)

Webxml

ltservletgt

ltservlet-namegtCookieExampleltservlet-namegt

ltservlet-classgtCookieExampleltservlet-classgt

ltservletgt

ltservlet-mappinggt

ltservlet-namegtCookieExampleltservlet-namegt lturl-patterngtservletsservletCookieExamplelturl-patterngt

ltservlet-mappinggt

Cookies Example

Your browser is sending the following cookiesCookie Name venkatCookie Value 90Create a cookie to send to your browserName Value

Submit Query

Venkta

Venkat

How Do We Need HTTP StateWeb applications need to track the users

across a series of requests

Online shopping (eg Order books)

ndash Financial portfolio manager

ndash Movie listings HTTP does not support directly Need a mechanism to maintain state about a series of requests

from the same user ( or originating from the same browser) over some period of time

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

Number of problems that arise from the fact that HTTP is a stateless protocol In particular when you are doing on-line shopping it is a real annoyance that the Web server cant easily remember previous transactions

This makes applications like shopping carts very problematic when you add an entry to your cart how does the server know whats already in your cart Even if servers did retain contextual information youd still have problems with e-commerce how does the server remember what you were buying

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( ) and removeAttribute( ) methods of HttpSession manage these

bindings

It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

Reading Cookies from the Client Call requestgetCookies ndash This yields an array of Cookie objects bull Loop down the array calling getName on each

entry until you find the cookie of interest ndash Use the value (getValue) in application-specific way

String cookieName = userID

Cookie[] cookies = requestgetCookies()

if (cookies = null)

for(int i=0 iltcookieslength i++)

Cookie cookie = cookies[i]

if (cookieNameequals(cookiegetName()))

doSomethingWith(cookiegetValue())

Using Cookie MethodsgetDomainsetDomain

ndash Lets you specify domain to which cookie applies Current

host must be part of domain specified

bull getMaxAgesetMaxAge

ndash Getssets the cookie expiration time (in seconds) If you

fail to set this cookie applies to current browsing session

only See LongLivedCookie helper class given earlier

bull getName

ndash Gets the cookie name There is no setName method you

supply name to constructor For incoming cookie array

you use getName to find the cookie of interest

getPathsetPath

ndash Getssets the path to which cookie applies If unspecified

cookie applies to URLs that are within or below directory containing current page

bull getSecuresetSecure

ndash Getssets flag indicating whether cookie should apply

only to SSL connections or to all connections

bull getValuesetValue

ndash Getssets value associated with cookie For new cookies

you supply value to constructor not to setValue For

incoming cookie array you use getName to find the

cookie of interest then call getValue on the result If you

set the value of an incoming cookie you still have to send

it back out with responseaddCookie

Advantages

ndash Very easy to implement

ndash Highly customizable

ndash Persist across browser shut-downs

Disadvantages

ndash Often users turn off cookies for privacy

or security reason

ndash Not quite universal browser support

Add Cookiehtml

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=post

action=httplocalhost8080examplesservletsservletAddCookieServletgt

ltBgtEnter a value for MyCookieltBgt

ltinput type=textbox name=data size=25 value=gt

ltinput type=submit value=Submitgt

ltformgt

ltbodygt

lthtmlgt

AddCookie Serveletjava

import javaio

import javaxservlet

import javaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

pwclose()

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=postldquo action=httplocalhost8080examplesservletsservletPostParametersServletgt

lttablegt

lttrgt

lttdgtltBgtEmployeelttdgt

lttdgtltinput type=textbox name=e size=25 value=gtlttdgt

lttrgt

lttrgt

lttdgtltBgtPhonelttdgt

lttdgtltinput type=textbox name=p size=25 value=gtlttdgt

lttrgt

lttablegt

ltinput type=submit value=Submitgt

ltbodygt

lthtmlgt

import javaioimport javaxservletimport javaxservlethttp public class CookieExample extends HttpServlet public void doGet(HttpServletRequest request HttpServletResponse response) throws IOException ServletException responsesetContentType(texthtml) PrintWriter out = responsegetWriter() print out cookies Cookie[] cookies = requestgetCookies() for (int i = 0 i lt cookieslength i++) Cookie c = cookies[i] String name = cgetName() String value = cgetValue() outprintln(name + = + value)

set a cookie

String name = requestgetParameter(cookieName)

if (name = null ampamp namelength() gt 0)

String value = requestgetParameter(cookieValue)

Cookie c = new Cookie(name value)

responseaddCookie(c)

Webxml

ltservletgt

ltservlet-namegtCookieExampleltservlet-namegt

ltservlet-classgtCookieExampleltservlet-classgt

ltservletgt

ltservlet-mappinggt

ltservlet-namegtCookieExampleltservlet-namegt lturl-patterngtservletsservletCookieExamplelturl-patterngt

ltservlet-mappinggt

Cookies Example

Your browser is sending the following cookiesCookie Name venkatCookie Value 90Create a cookie to send to your browserName Value

Submit Query

Venkta

Venkat

How Do We Need HTTP StateWeb applications need to track the users

across a series of requests

Online shopping (eg Order books)

ndash Financial portfolio manager

ndash Movie listings HTTP does not support directly Need a mechanism to maintain state about a series of requests

from the same user ( or originating from the same browser) over some period of time

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

Number of problems that arise from the fact that HTTP is a stateless protocol In particular when you are doing on-line shopping it is a real annoyance that the Web server cant easily remember previous transactions

This makes applications like shopping carts very problematic when you add an entry to your cart how does the server know whats already in your cart Even if servers did retain contextual information youd still have problems with e-commerce how does the server remember what you were buying

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( ) and removeAttribute( ) methods of HttpSession manage these

bindings

It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

Using Cookie MethodsgetDomainsetDomain

ndash Lets you specify domain to which cookie applies Current

host must be part of domain specified

bull getMaxAgesetMaxAge

ndash Getssets the cookie expiration time (in seconds) If you

fail to set this cookie applies to current browsing session

only See LongLivedCookie helper class given earlier

bull getName

ndash Gets the cookie name There is no setName method you

supply name to constructor For incoming cookie array

you use getName to find the cookie of interest

getPathsetPath

ndash Getssets the path to which cookie applies If unspecified

cookie applies to URLs that are within or below directory containing current page

bull getSecuresetSecure

ndash Getssets flag indicating whether cookie should apply

only to SSL connections or to all connections

bull getValuesetValue

ndash Getssets value associated with cookie For new cookies

you supply value to constructor not to setValue For

incoming cookie array you use getName to find the

cookie of interest then call getValue on the result If you

set the value of an incoming cookie you still have to send

it back out with responseaddCookie

Advantages

ndash Very easy to implement

ndash Highly customizable

ndash Persist across browser shut-downs

Disadvantages

ndash Often users turn off cookies for privacy

or security reason

ndash Not quite universal browser support

Add Cookiehtml

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=post

action=httplocalhost8080examplesservletsservletAddCookieServletgt

ltBgtEnter a value for MyCookieltBgt

ltinput type=textbox name=data size=25 value=gt

ltinput type=submit value=Submitgt

ltformgt

ltbodygt

lthtmlgt

AddCookie Serveletjava

import javaio

import javaxservlet

import javaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

pwclose()

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=postldquo action=httplocalhost8080examplesservletsservletPostParametersServletgt

lttablegt

lttrgt

lttdgtltBgtEmployeelttdgt

lttdgtltinput type=textbox name=e size=25 value=gtlttdgt

lttrgt

lttrgt

lttdgtltBgtPhonelttdgt

lttdgtltinput type=textbox name=p size=25 value=gtlttdgt

lttrgt

lttablegt

ltinput type=submit value=Submitgt

ltbodygt

lthtmlgt

import javaioimport javaxservletimport javaxservlethttp public class CookieExample extends HttpServlet public void doGet(HttpServletRequest request HttpServletResponse response) throws IOException ServletException responsesetContentType(texthtml) PrintWriter out = responsegetWriter() print out cookies Cookie[] cookies = requestgetCookies() for (int i = 0 i lt cookieslength i++) Cookie c = cookies[i] String name = cgetName() String value = cgetValue() outprintln(name + = + value)

set a cookie

String name = requestgetParameter(cookieName)

if (name = null ampamp namelength() gt 0)

String value = requestgetParameter(cookieValue)

Cookie c = new Cookie(name value)

responseaddCookie(c)

Webxml

ltservletgt

ltservlet-namegtCookieExampleltservlet-namegt

ltservlet-classgtCookieExampleltservlet-classgt

ltservletgt

ltservlet-mappinggt

ltservlet-namegtCookieExampleltservlet-namegt lturl-patterngtservletsservletCookieExamplelturl-patterngt

ltservlet-mappinggt

Cookies Example

Your browser is sending the following cookiesCookie Name venkatCookie Value 90Create a cookie to send to your browserName Value

Submit Query

Venkta

Venkat

How Do We Need HTTP StateWeb applications need to track the users

across a series of requests

Online shopping (eg Order books)

ndash Financial portfolio manager

ndash Movie listings HTTP does not support directly Need a mechanism to maintain state about a series of requests

from the same user ( or originating from the same browser) over some period of time

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

Number of problems that arise from the fact that HTTP is a stateless protocol In particular when you are doing on-line shopping it is a real annoyance that the Web server cant easily remember previous transactions

This makes applications like shopping carts very problematic when you add an entry to your cart how does the server know whats already in your cart Even if servers did retain contextual information youd still have problems with e-commerce how does the server remember what you were buying

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( ) and removeAttribute( ) methods of HttpSession manage these

bindings

It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

getPathsetPath

ndash Getssets the path to which cookie applies If unspecified

cookie applies to URLs that are within or below directory containing current page

bull getSecuresetSecure

ndash Getssets flag indicating whether cookie should apply

only to SSL connections or to all connections

bull getValuesetValue

ndash Getssets value associated with cookie For new cookies

you supply value to constructor not to setValue For

incoming cookie array you use getName to find the

cookie of interest then call getValue on the result If you

set the value of an incoming cookie you still have to send

it back out with responseaddCookie

Advantages

ndash Very easy to implement

ndash Highly customizable

ndash Persist across browser shut-downs

Disadvantages

ndash Often users turn off cookies for privacy

or security reason

ndash Not quite universal browser support

Add Cookiehtml

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=post

action=httplocalhost8080examplesservletsservletAddCookieServletgt

ltBgtEnter a value for MyCookieltBgt

ltinput type=textbox name=data size=25 value=gt

ltinput type=submit value=Submitgt

ltformgt

ltbodygt

lthtmlgt

AddCookie Serveletjava

import javaio

import javaxservlet

import javaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

pwclose()

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=postldquo action=httplocalhost8080examplesservletsservletPostParametersServletgt

lttablegt

lttrgt

lttdgtltBgtEmployeelttdgt

lttdgtltinput type=textbox name=e size=25 value=gtlttdgt

lttrgt

lttrgt

lttdgtltBgtPhonelttdgt

lttdgtltinput type=textbox name=p size=25 value=gtlttdgt

lttrgt

lttablegt

ltinput type=submit value=Submitgt

ltbodygt

lthtmlgt

import javaioimport javaxservletimport javaxservlethttp public class CookieExample extends HttpServlet public void doGet(HttpServletRequest request HttpServletResponse response) throws IOException ServletException responsesetContentType(texthtml) PrintWriter out = responsegetWriter() print out cookies Cookie[] cookies = requestgetCookies() for (int i = 0 i lt cookieslength i++) Cookie c = cookies[i] String name = cgetName() String value = cgetValue() outprintln(name + = + value)

set a cookie

String name = requestgetParameter(cookieName)

if (name = null ampamp namelength() gt 0)

String value = requestgetParameter(cookieValue)

Cookie c = new Cookie(name value)

responseaddCookie(c)

Webxml

ltservletgt

ltservlet-namegtCookieExampleltservlet-namegt

ltservlet-classgtCookieExampleltservlet-classgt

ltservletgt

ltservlet-mappinggt

ltservlet-namegtCookieExampleltservlet-namegt lturl-patterngtservletsservletCookieExamplelturl-patterngt

ltservlet-mappinggt

Cookies Example

Your browser is sending the following cookiesCookie Name venkatCookie Value 90Create a cookie to send to your browserName Value

Submit Query

Venkta

Venkat

How Do We Need HTTP StateWeb applications need to track the users

across a series of requests

Online shopping (eg Order books)

ndash Financial portfolio manager

ndash Movie listings HTTP does not support directly Need a mechanism to maintain state about a series of requests

from the same user ( or originating from the same browser) over some period of time

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

Number of problems that arise from the fact that HTTP is a stateless protocol In particular when you are doing on-line shopping it is a real annoyance that the Web server cant easily remember previous transactions

This makes applications like shopping carts very problematic when you add an entry to your cart how does the server know whats already in your cart Even if servers did retain contextual information youd still have problems with e-commerce how does the server remember what you were buying

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( ) and removeAttribute( ) methods of HttpSession manage these

bindings

It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

Advantages

ndash Very easy to implement

ndash Highly customizable

ndash Persist across browser shut-downs

Disadvantages

ndash Often users turn off cookies for privacy

or security reason

ndash Not quite universal browser support

Add Cookiehtml

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=post

action=httplocalhost8080examplesservletsservletAddCookieServletgt

ltBgtEnter a value for MyCookieltBgt

ltinput type=textbox name=data size=25 value=gt

ltinput type=submit value=Submitgt

ltformgt

ltbodygt

lthtmlgt

AddCookie Serveletjava

import javaio

import javaxservlet

import javaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

pwclose()

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=postldquo action=httplocalhost8080examplesservletsservletPostParametersServletgt

lttablegt

lttrgt

lttdgtltBgtEmployeelttdgt

lttdgtltinput type=textbox name=e size=25 value=gtlttdgt

lttrgt

lttrgt

lttdgtltBgtPhonelttdgt

lttdgtltinput type=textbox name=p size=25 value=gtlttdgt

lttrgt

lttablegt

ltinput type=submit value=Submitgt

ltbodygt

lthtmlgt

import javaioimport javaxservletimport javaxservlethttp public class CookieExample extends HttpServlet public void doGet(HttpServletRequest request HttpServletResponse response) throws IOException ServletException responsesetContentType(texthtml) PrintWriter out = responsegetWriter() print out cookies Cookie[] cookies = requestgetCookies() for (int i = 0 i lt cookieslength i++) Cookie c = cookies[i] String name = cgetName() String value = cgetValue() outprintln(name + = + value)

set a cookie

String name = requestgetParameter(cookieName)

if (name = null ampamp namelength() gt 0)

String value = requestgetParameter(cookieValue)

Cookie c = new Cookie(name value)

responseaddCookie(c)

Webxml

ltservletgt

ltservlet-namegtCookieExampleltservlet-namegt

ltservlet-classgtCookieExampleltservlet-classgt

ltservletgt

ltservlet-mappinggt

ltservlet-namegtCookieExampleltservlet-namegt lturl-patterngtservletsservletCookieExamplelturl-patterngt

ltservlet-mappinggt

Cookies Example

Your browser is sending the following cookiesCookie Name venkatCookie Value 90Create a cookie to send to your browserName Value

Submit Query

Venkta

Venkat

How Do We Need HTTP StateWeb applications need to track the users

across a series of requests

Online shopping (eg Order books)

ndash Financial portfolio manager

ndash Movie listings HTTP does not support directly Need a mechanism to maintain state about a series of requests

from the same user ( or originating from the same browser) over some period of time

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

Number of problems that arise from the fact that HTTP is a stateless protocol In particular when you are doing on-line shopping it is a real annoyance that the Web server cant easily remember previous transactions

This makes applications like shopping carts very problematic when you add an entry to your cart how does the server know whats already in your cart Even if servers did retain contextual information youd still have problems with e-commerce how does the server remember what you were buying

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( ) and removeAttribute( ) methods of HttpSession manage these

bindings

It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

Add Cookiehtml

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=post

action=httplocalhost8080examplesservletsservletAddCookieServletgt

ltBgtEnter a value for MyCookieltBgt

ltinput type=textbox name=data size=25 value=gt

ltinput type=submit value=Submitgt

ltformgt

ltbodygt

lthtmlgt

AddCookie Serveletjava

import javaio

import javaxservlet

import javaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

pwclose()

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=postldquo action=httplocalhost8080examplesservletsservletPostParametersServletgt

lttablegt

lttrgt

lttdgtltBgtEmployeelttdgt

lttdgtltinput type=textbox name=e size=25 value=gtlttdgt

lttrgt

lttrgt

lttdgtltBgtPhonelttdgt

lttdgtltinput type=textbox name=p size=25 value=gtlttdgt

lttrgt

lttablegt

ltinput type=submit value=Submitgt

ltbodygt

lthtmlgt

import javaioimport javaxservletimport javaxservlethttp public class CookieExample extends HttpServlet public void doGet(HttpServletRequest request HttpServletResponse response) throws IOException ServletException responsesetContentType(texthtml) PrintWriter out = responsegetWriter() print out cookies Cookie[] cookies = requestgetCookies() for (int i = 0 i lt cookieslength i++) Cookie c = cookies[i] String name = cgetName() String value = cgetValue() outprintln(name + = + value)

set a cookie

String name = requestgetParameter(cookieName)

if (name = null ampamp namelength() gt 0)

String value = requestgetParameter(cookieValue)

Cookie c = new Cookie(name value)

responseaddCookie(c)

Webxml

ltservletgt

ltservlet-namegtCookieExampleltservlet-namegt

ltservlet-classgtCookieExampleltservlet-classgt

ltservletgt

ltservlet-mappinggt

ltservlet-namegtCookieExampleltservlet-namegt lturl-patterngtservletsservletCookieExamplelturl-patterngt

ltservlet-mappinggt

Cookies Example

Your browser is sending the following cookiesCookie Name venkatCookie Value 90Create a cookie to send to your browserName Value

Submit Query

Venkta

Venkat

How Do We Need HTTP StateWeb applications need to track the users

across a series of requests

Online shopping (eg Order books)

ndash Financial portfolio manager

ndash Movie listings HTTP does not support directly Need a mechanism to maintain state about a series of requests

from the same user ( or originating from the same browser) over some period of time

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

Number of problems that arise from the fact that HTTP is a stateless protocol In particular when you are doing on-line shopping it is a real annoyance that the Web server cant easily remember previous transactions

This makes applications like shopping carts very problematic when you add an entry to your cart how does the server know whats already in your cart Even if servers did retain contextual information youd still have problems with e-commerce how does the server remember what you were buying

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( ) and removeAttribute( ) methods of HttpSession manage these

bindings

It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

AddCookie Serveletjava

import javaio

import javaxservlet

import javaxservlethttp

public class AddCookieServlet extends HttpServlet

public void doPost(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get parameter from HTTP request

String data = requestgetParameter(data)

Create cookie

Cookie cookie = new Cookie(MyCookie data)

Add cookie to HTTP response

responseaddCookie(cookie)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

pwclose()

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=postldquo action=httplocalhost8080examplesservletsservletPostParametersServletgt

lttablegt

lttrgt

lttdgtltBgtEmployeelttdgt

lttdgtltinput type=textbox name=e size=25 value=gtlttdgt

lttrgt

lttrgt

lttdgtltBgtPhonelttdgt

lttdgtltinput type=textbox name=p size=25 value=gtlttdgt

lttrgt

lttablegt

ltinput type=submit value=Submitgt

ltbodygt

lthtmlgt

import javaioimport javaxservletimport javaxservlethttp public class CookieExample extends HttpServlet public void doGet(HttpServletRequest request HttpServletResponse response) throws IOException ServletException responsesetContentType(texthtml) PrintWriter out = responsegetWriter() print out cookies Cookie[] cookies = requestgetCookies() for (int i = 0 i lt cookieslength i++) Cookie c = cookies[i] String name = cgetName() String value = cgetValue() outprintln(name + = + value)

set a cookie

String name = requestgetParameter(cookieName)

if (name = null ampamp namelength() gt 0)

String value = requestgetParameter(cookieValue)

Cookie c = new Cookie(name value)

responseaddCookie(c)

Webxml

ltservletgt

ltservlet-namegtCookieExampleltservlet-namegt

ltservlet-classgtCookieExampleltservlet-classgt

ltservletgt

ltservlet-mappinggt

ltservlet-namegtCookieExampleltservlet-namegt lturl-patterngtservletsservletCookieExamplelturl-patterngt

ltservlet-mappinggt

Cookies Example

Your browser is sending the following cookiesCookie Name venkatCookie Value 90Create a cookie to send to your browserName Value

Submit Query

Venkta

Venkat

How Do We Need HTTP StateWeb applications need to track the users

across a series of requests

Online shopping (eg Order books)

ndash Financial portfolio manager

ndash Movie listings HTTP does not support directly Need a mechanism to maintain state about a series of requests

from the same user ( or originating from the same browser) over some period of time

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

Number of problems that arise from the fact that HTTP is a stateless protocol In particular when you are doing on-line shopping it is a real annoyance that the Web server cant easily remember previous transactions

This makes applications like shopping carts very problematic when you add an entry to your cart how does the server know whats already in your cart Even if servers did retain contextual information youd still have problems with e-commerce how does the server remember what you were buying

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( ) and removeAttribute( ) methods of HttpSession manage these

bindings

It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

Write output to browser

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprintln(ltBgtMyCookie has been set to)

pwprintln(data)

pwclose()

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=postldquo action=httplocalhost8080examplesservletsservletPostParametersServletgt

lttablegt

lttrgt

lttdgtltBgtEmployeelttdgt

lttdgtltinput type=textbox name=e size=25 value=gtlttdgt

lttrgt

lttrgt

lttdgtltBgtPhonelttdgt

lttdgtltinput type=textbox name=p size=25 value=gtlttdgt

lttrgt

lttablegt

ltinput type=submit value=Submitgt

ltbodygt

lthtmlgt

import javaioimport javaxservletimport javaxservlethttp public class CookieExample extends HttpServlet public void doGet(HttpServletRequest request HttpServletResponse response) throws IOException ServletException responsesetContentType(texthtml) PrintWriter out = responsegetWriter() print out cookies Cookie[] cookies = requestgetCookies() for (int i = 0 i lt cookieslength i++) Cookie c = cookies[i] String name = cgetName() String value = cgetValue() outprintln(name + = + value)

set a cookie

String name = requestgetParameter(cookieName)

if (name = null ampamp namelength() gt 0)

String value = requestgetParameter(cookieValue)

Cookie c = new Cookie(name value)

responseaddCookie(c)

Webxml

ltservletgt

ltservlet-namegtCookieExampleltservlet-namegt

ltservlet-classgtCookieExampleltservlet-classgt

ltservletgt

ltservlet-mappinggt

ltservlet-namegtCookieExampleltservlet-namegt lturl-patterngtservletsservletCookieExamplelturl-patterngt

ltservlet-mappinggt

Cookies Example

Your browser is sending the following cookiesCookie Name venkatCookie Value 90Create a cookie to send to your browserName Value

Submit Query

Venkta

Venkat

How Do We Need HTTP StateWeb applications need to track the users

across a series of requests

Online shopping (eg Order books)

ndash Financial portfolio manager

ndash Movie listings HTTP does not support directly Need a mechanism to maintain state about a series of requests

from the same user ( or originating from the same browser) over some period of time

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

Number of problems that arise from the fact that HTTP is a stateless protocol In particular when you are doing on-line shopping it is a real annoyance that the Web server cant easily remember previous transactions

This makes applications like shopping carts very problematic when you add an entry to your cart how does the server know whats already in your cart Even if servers did retain contextual information youd still have problems with e-commerce how does the server remember what you were buying

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( ) and removeAttribute( ) methods of HttpSession manage these

bindings

It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

lthtmlgt

ltbodygt

ltcentergt

ltform name=Form1

method=postldquo action=httplocalhost8080examplesservletsservletPostParametersServletgt

lttablegt

lttrgt

lttdgtltBgtEmployeelttdgt

lttdgtltinput type=textbox name=e size=25 value=gtlttdgt

lttrgt

lttrgt

lttdgtltBgtPhonelttdgt

lttdgtltinput type=textbox name=p size=25 value=gtlttdgt

lttrgt

lttablegt

ltinput type=submit value=Submitgt

ltbodygt

lthtmlgt

import javaioimport javaxservletimport javaxservlethttp public class CookieExample extends HttpServlet public void doGet(HttpServletRequest request HttpServletResponse response) throws IOException ServletException responsesetContentType(texthtml) PrintWriter out = responsegetWriter() print out cookies Cookie[] cookies = requestgetCookies() for (int i = 0 i lt cookieslength i++) Cookie c = cookies[i] String name = cgetName() String value = cgetValue() outprintln(name + = + value)

set a cookie

String name = requestgetParameter(cookieName)

if (name = null ampamp namelength() gt 0)

String value = requestgetParameter(cookieValue)

Cookie c = new Cookie(name value)

responseaddCookie(c)

Webxml

ltservletgt

ltservlet-namegtCookieExampleltservlet-namegt

ltservlet-classgtCookieExampleltservlet-classgt

ltservletgt

ltservlet-mappinggt

ltservlet-namegtCookieExampleltservlet-namegt lturl-patterngtservletsservletCookieExamplelturl-patterngt

ltservlet-mappinggt

Cookies Example

Your browser is sending the following cookiesCookie Name venkatCookie Value 90Create a cookie to send to your browserName Value

Submit Query

Venkta

Venkat

How Do We Need HTTP StateWeb applications need to track the users

across a series of requests

Online shopping (eg Order books)

ndash Financial portfolio manager

ndash Movie listings HTTP does not support directly Need a mechanism to maintain state about a series of requests

from the same user ( or originating from the same browser) over some period of time

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

Number of problems that arise from the fact that HTTP is a stateless protocol In particular when you are doing on-line shopping it is a real annoyance that the Web server cant easily remember previous transactions

This makes applications like shopping carts very problematic when you add an entry to your cart how does the server know whats already in your cart Even if servers did retain contextual information youd still have problems with e-commerce how does the server remember what you were buying

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( ) and removeAttribute( ) methods of HttpSession manage these

bindings

It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

import javaioimport javaxservletimport javaxservlethttp public class CookieExample extends HttpServlet public void doGet(HttpServletRequest request HttpServletResponse response) throws IOException ServletException responsesetContentType(texthtml) PrintWriter out = responsegetWriter() print out cookies Cookie[] cookies = requestgetCookies() for (int i = 0 i lt cookieslength i++) Cookie c = cookies[i] String name = cgetName() String value = cgetValue() outprintln(name + = + value)

set a cookie

String name = requestgetParameter(cookieName)

if (name = null ampamp namelength() gt 0)

String value = requestgetParameter(cookieValue)

Cookie c = new Cookie(name value)

responseaddCookie(c)

Webxml

ltservletgt

ltservlet-namegtCookieExampleltservlet-namegt

ltservlet-classgtCookieExampleltservlet-classgt

ltservletgt

ltservlet-mappinggt

ltservlet-namegtCookieExampleltservlet-namegt lturl-patterngtservletsservletCookieExamplelturl-patterngt

ltservlet-mappinggt

Cookies Example

Your browser is sending the following cookiesCookie Name venkatCookie Value 90Create a cookie to send to your browserName Value

Submit Query

Venkta

Venkat

How Do We Need HTTP StateWeb applications need to track the users

across a series of requests

Online shopping (eg Order books)

ndash Financial portfolio manager

ndash Movie listings HTTP does not support directly Need a mechanism to maintain state about a series of requests

from the same user ( or originating from the same browser) over some period of time

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

Number of problems that arise from the fact that HTTP is a stateless protocol In particular when you are doing on-line shopping it is a real annoyance that the Web server cant easily remember previous transactions

This makes applications like shopping carts very problematic when you add an entry to your cart how does the server know whats already in your cart Even if servers did retain contextual information youd still have problems with e-commerce how does the server remember what you were buying

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( ) and removeAttribute( ) methods of HttpSession manage these

bindings

It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

set a cookie

String name = requestgetParameter(cookieName)

if (name = null ampamp namelength() gt 0)

String value = requestgetParameter(cookieValue)

Cookie c = new Cookie(name value)

responseaddCookie(c)

Webxml

ltservletgt

ltservlet-namegtCookieExampleltservlet-namegt

ltservlet-classgtCookieExampleltservlet-classgt

ltservletgt

ltservlet-mappinggt

ltservlet-namegtCookieExampleltservlet-namegt lturl-patterngtservletsservletCookieExamplelturl-patterngt

ltservlet-mappinggt

Cookies Example

Your browser is sending the following cookiesCookie Name venkatCookie Value 90Create a cookie to send to your browserName Value

Submit Query

Venkta

Venkat

How Do We Need HTTP StateWeb applications need to track the users

across a series of requests

Online shopping (eg Order books)

ndash Financial portfolio manager

ndash Movie listings HTTP does not support directly Need a mechanism to maintain state about a series of requests

from the same user ( or originating from the same browser) over some period of time

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

Number of problems that arise from the fact that HTTP is a stateless protocol In particular when you are doing on-line shopping it is a real annoyance that the Web server cant easily remember previous transactions

This makes applications like shopping carts very problematic when you add an entry to your cart how does the server know whats already in your cart Even if servers did retain contextual information youd still have problems with e-commerce how does the server remember what you were buying

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( ) and removeAttribute( ) methods of HttpSession manage these

bindings

It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

Webxml

ltservletgt

ltservlet-namegtCookieExampleltservlet-namegt

ltservlet-classgtCookieExampleltservlet-classgt

ltservletgt

ltservlet-mappinggt

ltservlet-namegtCookieExampleltservlet-namegt lturl-patterngtservletsservletCookieExamplelturl-patterngt

ltservlet-mappinggt

Cookies Example

Your browser is sending the following cookiesCookie Name venkatCookie Value 90Create a cookie to send to your browserName Value

Submit Query

Venkta

Venkat

How Do We Need HTTP StateWeb applications need to track the users

across a series of requests

Online shopping (eg Order books)

ndash Financial portfolio manager

ndash Movie listings HTTP does not support directly Need a mechanism to maintain state about a series of requests

from the same user ( or originating from the same browser) over some period of time

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

Number of problems that arise from the fact that HTTP is a stateless protocol In particular when you are doing on-line shopping it is a real annoyance that the Web server cant easily remember previous transactions

This makes applications like shopping carts very problematic when you add an entry to your cart how does the server know whats already in your cart Even if servers did retain contextual information youd still have problems with e-commerce how does the server remember what you were buying

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( ) and removeAttribute( ) methods of HttpSession manage these

bindings

It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

Cookies Example

Your browser is sending the following cookiesCookie Name venkatCookie Value 90Create a cookie to send to your browserName Value

Submit Query

Venkta

Venkat

How Do We Need HTTP StateWeb applications need to track the users

across a series of requests

Online shopping (eg Order books)

ndash Financial portfolio manager

ndash Movie listings HTTP does not support directly Need a mechanism to maintain state about a series of requests

from the same user ( or originating from the same browser) over some period of time

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

Number of problems that arise from the fact that HTTP is a stateless protocol In particular when you are doing on-line shopping it is a real annoyance that the Web server cant easily remember previous transactions

This makes applications like shopping carts very problematic when you add an entry to your cart how does the server know whats already in your cart Even if servers did retain contextual information youd still have problems with e-commerce how does the server remember what you were buying

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( ) and removeAttribute( ) methods of HttpSession manage these

bindings

It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

How Do We Need HTTP StateWeb applications need to track the users

across a series of requests

Online shopping (eg Order books)

ndash Financial portfolio manager

ndash Movie listings HTTP does not support directly Need a mechanism to maintain state about a series of requests

from the same user ( or originating from the same browser) over some period of time

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

Number of problems that arise from the fact that HTTP is a stateless protocol In particular when you are doing on-line shopping it is a real annoyance that the Web server cant easily remember previous transactions

This makes applications like shopping carts very problematic when you add an entry to your cart how does the server know whats already in your cart Even if servers did retain contextual information youd still have problems with e-commerce how does the server remember what you were buying

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( ) and removeAttribute( ) methods of HttpSession manage these

bindings

It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

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

Number of problems that arise from the fact that HTTP is a stateless protocol In particular when you are doing on-line shopping it is a real annoyance that the Web server cant easily remember previous transactions

This makes applications like shopping carts very problematic when you add an entry to your cart how does the server know whats already in your cart Even if servers did retain contextual information youd still have problems with e-commerce how does the server remember what you were buying

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( ) and removeAttribute( ) methods of HttpSession manage these

bindings

It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

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( ) and removeAttribute( ) methods of HttpSession manage these

bindings

It is important to note that session state is shared among all the servlets that are associated with a particular client

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

HTTP protocol

HTTP is a stateless protocol A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests

For example when a web server is required to customize the content of a web page for a user the web application may have to track the users progress from page to page

A common solution is the use of HTTP cookies Other methods include server side sessions hidden variables (when the current page contains a form) and URL-rewriting using URI-encoded parameters eg

Cookie

URL Rewriting

Hidden form fields

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

HTTP session An HTTP session is a sequence of network request-response

transactions An HTTP client initiates a request by establishing a

Transmission Control Protocol (TCP) connection to a particular port on a server (typically port 80

An HTTP server listening on that port waits for a clients request message

Upon receiving the request the server sends back a status line such as HTTP11 200 OK and a message of its own

The body of this message is typically the requested resource although an error message or other information may also be returned

Mehtods GET POST and HEAD OPTIONS PUT DELETE TRACE and

CONNECT

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

Some methods (for example HEAD GET OPTIONS and TRACE) are defined as safe which means they are intended only for information retrieval and should not change the state of the server In other words they should not have side effects beyond relatively harmless effects such as logging caching the serving of banner advertisements or incrementing a web counter

POST PUT and DELETE are intended for actions that may cause side effects either on the server or external side effects such as financial tra

nsactions or transmission of email HTTP Status code

1 1xx Informational 2 2xx Success 3 3xx Redirection 4 4xx Client Error 5 5xx Server Error

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

Session Lifecycle API Sessions usually timeout after 30 minutes of inactivity A different timeout may be set by server admin

public void invalidate()

ndash Expires the session and unbinds all objects with it

boolean sessionisNew()

ndash Determines if session is new to client (not page)

long sessiongetCreationTime()

ndash Returns time at which session was first created

long sessiongetLastAccessedTime()

ndash Returns when the user last accessed the server

getMaxInactiveInterval setMaxInactiveInterval

ndash Gets or sets the amount of time session should go without access before being invalidated

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

import javaio

import javautil

import javaxservlet

import javaxservlethttp

public class DateServlet extends HttpServlet

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

Get the HttpSession object

HttpSession hs = requestgetSession(true)

Get writer

responsesetContentType(texthtml)

PrintWriter pw = responsegetWriter()

pwprint(ltBgt)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

Display datetime of last access

Date date = (Date)hsgetAttribute(date)

if(date = null)

pwprint(Last access + date + ltbrgt)

Display current datetime

date = new Date()

hssetAttribute(date date)

pwprintln(Current date + date)

The getAttribute( ) method is called to obtain the object that is bound to the

name ldquodaterdquo That object is a Date object that encapsulates the date and time when this

page was last accessed A Date object encapsulating the current date and time is then created The setAttribute( ) method is called to bind the name ldquodaterdquo to this object

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

URL Rewriting You can append some extra data on the end of each

URL that identifies the session and the server can associate that session identifier with data it has stored about that session

This is also an excellent solution and even has the advantage that it works with browsers that dont support cookies or where the user has disabled cookies

URL rewriting provides you with another session tracking alternative

URL rewriting is a method in which the requested URL is modified to include a session ID There are several ways to perform URL rewriting You are going to look at one method that is provided by the Servlet API

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

URLs can be rewritten or encoded to include session information

bull URL rewriting usually includes a session id bull id can be sent as extra path information

ndash httpservletRewritten688

ndash Works well if no need for extra path info

bull id can be sent as an added parameter

ndash httpservletRewrittensessionid=688

Advantages

ndash Let user remain anonymous

ndash They are universally supported(most styles)

bull Disadvantages

ndash Tedious to rewrite all URLs

ndash Only works for dynamically created documents

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

URL Rewriting

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

import javaxservlet

import javaxservlethttp

import javaio

import javautil

public class URLRewritingServlet extends HttpServlet

Initialize global variables

public void init(ServletConfig config)

throws ServletException

superinit(config)

Process the HTTP Get request

public void doGet(HttpServletRequest request

HttpServletResponse response)

throws ServletException IOException

responsesetContentType(texthtml)

PrintWriter out = responsegetWriter()

outprintln(lthtmlgt)

outprintln(ltheadgtlttitlegtURL Rewritinglttitlegtltheadgt)

outprintln(ltbodygt)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

Encode a URL string with the session id appended to it

String url = responseencodeRedirectURL(

httplocalhost8000servletcheckoutsid=5748)

Redirect the client to the new URL

responsesendRedirect(url)

outprintln(ltbodygtlthtmlgt)

outclose()

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

Hidden Form Fields Hidden form fields are another way to support session tracking Hidden form fields do not display in the browser but can be sent

back to the server by submit

ltFORM ACTION=servletShowParameters METHOD=POSTgt

ltINPUT TYPE=HIDDEN NAME=OCCUPATIONldquo VALUE=ENGINEERgt

ltINPUT TYPE=HIDDEN NAME=SESSIONID VALUE=194043gt

ltFORMgt

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)

Cont Fields can have identification (session id) or just

some thing to remember (occupation) Servlet reads the fields using reqgetParameter() Advantages ndash Universally supported ndash Allow anonymous users Disadvantages ndash Only works for a sequence of dynamically generated forms ndash Breaks down with static documents emailed documents

bookmarked documents ndash No browser shutdowns

  • Cookies
  • Cookie
  • Cont
  • Slide 4
  • Sending Cookies to the Client
  • Reading Cookies from the Client
  • Using Cookie Methods
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Webxml
  • Cookies Example
  • How Do We Need HTTP State
  • What is Session Tracking
  • Slide 20
  • Slide 21
  • HTTP session
  • Slide 23
  • Session Lifecycle API
  • Slide 25
  • Slide 26
  • URL Rewriting
  • Slide 28
  • URL Rewriting
  • Slide 30
  • Slide 31
  • Hidden Form Fields
  • Cont (2)