COMP9321 Web Applications EngineeringJava Servlets
Dr Moshe Chai Barukh
Service Oriented Computing Group CSE UNSW
Week 2
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 1 75
Different Layers in an Application
Different solutions for each layer
Presentation LayerI JSP XSLT CSS HTML
Business logicI Java classes
Data Access LayerI Data Access Objects
Data StoreI RDBMS OODBMS XML
Database
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 2 75
Typical HTML Interactions
The responses are generated dynamically (via a program) depending onyour input
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 3 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Tomcat Web container structure
bin (starstop the server) commonlib(shared libraries Tomcat-wide)
conf (server configuration files)
webapps (Web application base directory)
The structure of a Web Application Archive(war)
simplewar
indexhtml
WEB-INF
lib
classesmyFirstServletclass
webxml
To access the Web apphttplocalhost8080simpleindexhtml
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 5 75
Making servlets available in the Web container
1 Create the standard Web application directory structure
2 Write a servlet
3 Compile
4 Write a deployment descriptor (webxml)
5 Package all up into an archive file and name it appnamewar
6 Copy the war file into $CATALINA HOMEwebapps
7 The server detects the application and makes it available to the users
httplocalhost8080appname
There are tools developed designed to assist the programmers with theseries of tasks involved in writing Web applications
eg Ant tasks for Tomcat Eclipse Web Tools Platform (WTP)M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 6 75
How the Container handles a request ((HeadFirst) p42)
Web Server Machine
Container
Client
HTTPRequest
HttpServletRequest
HttpServletResponseContainer
Client
Servlet
Container
Client
Servlet
thread
requestresponse
Servlet
Servlet
Servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 7 75
How the Container handles a request ((HeadFirst) p42)
Container
Client
Servlet
threadrequest
response
Container
Servlet
thread
response
Container
Servlet
threadrequest
response
service()
service()
doGet()
GeneratedContent
HTTP Response
GeneratedContent
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 8 75
Your Servlet inherits rdquolifecyclerdquo methods
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()
ltltinterfacegtgtServlet
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()getInitParameter(String)getInitParameterNames()getServletContext()log(String)
GenericServlet
service(ServletRequest ServletResponse)service(HttpServletRequest HttpServletResponse)doGet(HttpServletRequest HttpServletResponse)doPost(HttpServletRequest HttpServletResponse)doHead(HttpServletRequest HttpServletResponse)doPut(HttpServletRequest HttpServletResponse)doOptions(HttpServletRequest HttpServletResponse)
HttpServlet
doGet(HttpServletRequestHttpServletResponse)myBusinessMethod()
MyServlet
javaxservletjavaxservlethttp
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 9 75
A typical Servlet looks like this
package comcomp9321
import javaio
import javaxservlet
import javaxservlethttp
public class OneServlet extends HttpServlet
public void doGet (HttpServletRequest req HttpServletResponse res)
throws ServletException IOException
ressetContentType(texthtml)
PrintWriter out = resgetWriter()
javautilDate today = new javautilDate()
outprintln(ltHTMLgtltBODYgtltH1gtOneServlet says it is now )
outprintln(today + ltH1gtltBODYgtltHTMLgt)
outclose()
Note No main() - the container calls the servlet methods like doGet() throughservice() How does the container know which servlet to call
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 10 75
Servlet Names
A servlet may have three namesI Name that the client usesI Name that used at deployment timeI Actual class name (ie OneServletclass)
All these names are declared and mapped in the deploymentdescriptor (webxml)Mapping servlet names improves your apprsquos flexibility and security
in webxml
ltweb-app xmlns=httpjavasuncomxmlnsj2ee
ltservletgt
ltservlet-namegtOneServletltservlet-namegt
ltservlet-classgtcomcomp9321OneServletltservlet-classgt
ltservletgt
ltservlet-mappinggt
ltservlet-namegtOneServletltservlet-namegt
lturl-patterngtoneservletlturl-patterngt
ltservlet-mappinggt
URL to the servlet - httplocalhost8080myApplicationoneservletM C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 11 75
A Lifecycle of a Servlet
The Web container controls the lifecycle of a servlet class
Container
Web Container Servlet Class Servlet Object
1001010000011010 10 000101
initialised
initialised
load class
Instantiate servlet
init()
service()
destroy()
handleclientrequests (doXX())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 12 75
Servletrsquos Life ((HeadFirst) p99)
lifecyclecalls
When itrsquos called What itrsquos for Overrideit
init() Container calls init() after theservlet instance is created butbefore the serlvet can serviceclientrsquos requests
Gives you a chance to ini-tialise your servlet before han-dling any requests
No
service() When the first client requestcomes in the container startsa new thread and calls ser-vice() method
This one looks at the re-quest and determines theHTTP method and invokesthe matching doXX() on theservlet
No
doXX() The service() method invokesappropriate doXX()
This is where your Servletcode begins This is themethod that is responsible forwhatever the servlet is sup-posed to be doing
Always
Maybe (eg getting a database connection) but not always
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 13 75
Why care about this initialisation details (HeadFirst) p104
Once the servlet is initialised the servlet gets access to two importantobjects
A ServletConfig object
I One ServletConfig object per servletI Use it to pass deploy-time information to the servlet (any info that
you do not want to hard-code into the servlet)I Use it to access the ServletContextI Parameters are configured in the deployment descriptor
A ServletContextI One ServletContext per Web application (they should have named it
AppContext)I Use it to access parameters that are Web application-wideI Use it as a kind of application bulletin-board where you can put up
info (called attributes) that other parts of the application can accessI Use it to get server info including the name and version of the
container etc
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 14 75
Why care about this initialisation details (HeadFirst) p104
does not exist
Servlet(initialised)
init(ServletConfig)
service()
destroy()
constructor
By the time servlet is running doXX() its got
a ServletConfigServletConfig
Servlet A Servlet B Servlet C
JSP A
ServletContext
ServletConfig
ServletConfig
ServletConfig
App-Wideparams
Servlet-Wideparams
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 15 75
ServletConfig Passing servlet configuration information
The Web container can pass some configuration information (eg initialparameters) for individual servlets in webxml
ltweb-appgtltservletgt
ltservlet-namegtDemoServletltservlet-namegtltservlet-classgtcomcomp9321ConfigDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtWebMasterltparam-namegtltparam-valuegtHelen Paikltparam-valuegt
ltinit-paramgtltinit-paramgt
ltparam-namegtWebMasterEmailltparam-namegtltparam-valuegthpaikwebmastercomltparam-valuegt
ltinit-paramgtltservletgtltservletgt
ltservlet-namegtSecondDemoServletltservlet-namegtltservlet-classgtcomcomp9321NextDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtlanguageltparam-namegtltparam-valuegtItalianltparam-valuegt
ltinit-paramgtltservletgt
ltweb-appgt
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 16 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Different Layers in an Application
Different solutions for each layer
Presentation LayerI JSP XSLT CSS HTML
Business logicI Java classes
Data Access LayerI Data Access Objects
Data StoreI RDBMS OODBMS XML
Database
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 2 75
Typical HTML Interactions
The responses are generated dynamically (via a program) depending onyour input
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 3 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Tomcat Web container structure
bin (starstop the server) commonlib(shared libraries Tomcat-wide)
conf (server configuration files)
webapps (Web application base directory)
The structure of a Web Application Archive(war)
simplewar
indexhtml
WEB-INF
lib
classesmyFirstServletclass
webxml
To access the Web apphttplocalhost8080simpleindexhtml
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 5 75
Making servlets available in the Web container
1 Create the standard Web application directory structure
2 Write a servlet
3 Compile
4 Write a deployment descriptor (webxml)
5 Package all up into an archive file and name it appnamewar
6 Copy the war file into $CATALINA HOMEwebapps
7 The server detects the application and makes it available to the users
httplocalhost8080appname
There are tools developed designed to assist the programmers with theseries of tasks involved in writing Web applications
eg Ant tasks for Tomcat Eclipse Web Tools Platform (WTP)M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 6 75
How the Container handles a request ((HeadFirst) p42)
Web Server Machine
Container
Client
HTTPRequest
HttpServletRequest
HttpServletResponseContainer
Client
Servlet
Container
Client
Servlet
thread
requestresponse
Servlet
Servlet
Servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 7 75
How the Container handles a request ((HeadFirst) p42)
Container
Client
Servlet
threadrequest
response
Container
Servlet
thread
response
Container
Servlet
threadrequest
response
service()
service()
doGet()
GeneratedContent
HTTP Response
GeneratedContent
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 8 75
Your Servlet inherits rdquolifecyclerdquo methods
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()
ltltinterfacegtgtServlet
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()getInitParameter(String)getInitParameterNames()getServletContext()log(String)
GenericServlet
service(ServletRequest ServletResponse)service(HttpServletRequest HttpServletResponse)doGet(HttpServletRequest HttpServletResponse)doPost(HttpServletRequest HttpServletResponse)doHead(HttpServletRequest HttpServletResponse)doPut(HttpServletRequest HttpServletResponse)doOptions(HttpServletRequest HttpServletResponse)
HttpServlet
doGet(HttpServletRequestHttpServletResponse)myBusinessMethod()
MyServlet
javaxservletjavaxservlethttp
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 9 75
A typical Servlet looks like this
package comcomp9321
import javaio
import javaxservlet
import javaxservlethttp
public class OneServlet extends HttpServlet
public void doGet (HttpServletRequest req HttpServletResponse res)
throws ServletException IOException
ressetContentType(texthtml)
PrintWriter out = resgetWriter()
javautilDate today = new javautilDate()
outprintln(ltHTMLgtltBODYgtltH1gtOneServlet says it is now )
outprintln(today + ltH1gtltBODYgtltHTMLgt)
outclose()
Note No main() - the container calls the servlet methods like doGet() throughservice() How does the container know which servlet to call
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 10 75
Servlet Names
A servlet may have three namesI Name that the client usesI Name that used at deployment timeI Actual class name (ie OneServletclass)
All these names are declared and mapped in the deploymentdescriptor (webxml)Mapping servlet names improves your apprsquos flexibility and security
in webxml
ltweb-app xmlns=httpjavasuncomxmlnsj2ee
ltservletgt
ltservlet-namegtOneServletltservlet-namegt
ltservlet-classgtcomcomp9321OneServletltservlet-classgt
ltservletgt
ltservlet-mappinggt
ltservlet-namegtOneServletltservlet-namegt
lturl-patterngtoneservletlturl-patterngt
ltservlet-mappinggt
URL to the servlet - httplocalhost8080myApplicationoneservletM C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 11 75
A Lifecycle of a Servlet
The Web container controls the lifecycle of a servlet class
Container
Web Container Servlet Class Servlet Object
1001010000011010 10 000101
initialised
initialised
load class
Instantiate servlet
init()
service()
destroy()
handleclientrequests (doXX())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 12 75
Servletrsquos Life ((HeadFirst) p99)
lifecyclecalls
When itrsquos called What itrsquos for Overrideit
init() Container calls init() after theservlet instance is created butbefore the serlvet can serviceclientrsquos requests
Gives you a chance to ini-tialise your servlet before han-dling any requests
No
service() When the first client requestcomes in the container startsa new thread and calls ser-vice() method
This one looks at the re-quest and determines theHTTP method and invokesthe matching doXX() on theservlet
No
doXX() The service() method invokesappropriate doXX()
This is where your Servletcode begins This is themethod that is responsible forwhatever the servlet is sup-posed to be doing
Always
Maybe (eg getting a database connection) but not always
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 13 75
Why care about this initialisation details (HeadFirst) p104
Once the servlet is initialised the servlet gets access to two importantobjects
A ServletConfig object
I One ServletConfig object per servletI Use it to pass deploy-time information to the servlet (any info that
you do not want to hard-code into the servlet)I Use it to access the ServletContextI Parameters are configured in the deployment descriptor
A ServletContextI One ServletContext per Web application (they should have named it
AppContext)I Use it to access parameters that are Web application-wideI Use it as a kind of application bulletin-board where you can put up
info (called attributes) that other parts of the application can accessI Use it to get server info including the name and version of the
container etc
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 14 75
Why care about this initialisation details (HeadFirst) p104
does not exist
Servlet(initialised)
init(ServletConfig)
service()
destroy()
constructor
By the time servlet is running doXX() its got
a ServletConfigServletConfig
Servlet A Servlet B Servlet C
JSP A
ServletContext
ServletConfig
ServletConfig
ServletConfig
App-Wideparams
Servlet-Wideparams
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 15 75
ServletConfig Passing servlet configuration information
The Web container can pass some configuration information (eg initialparameters) for individual servlets in webxml
ltweb-appgtltservletgt
ltservlet-namegtDemoServletltservlet-namegtltservlet-classgtcomcomp9321ConfigDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtWebMasterltparam-namegtltparam-valuegtHelen Paikltparam-valuegt
ltinit-paramgtltinit-paramgt
ltparam-namegtWebMasterEmailltparam-namegtltparam-valuegthpaikwebmastercomltparam-valuegt
ltinit-paramgtltservletgtltservletgt
ltservlet-namegtSecondDemoServletltservlet-namegtltservlet-classgtcomcomp9321NextDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtlanguageltparam-namegtltparam-valuegtItalianltparam-valuegt
ltinit-paramgtltservletgt
ltweb-appgt
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 16 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Typical HTML Interactions
The responses are generated dynamically (via a program) depending onyour input
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 3 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Tomcat Web container structure
bin (starstop the server) commonlib(shared libraries Tomcat-wide)
conf (server configuration files)
webapps (Web application base directory)
The structure of a Web Application Archive(war)
simplewar
indexhtml
WEB-INF
lib
classesmyFirstServletclass
webxml
To access the Web apphttplocalhost8080simpleindexhtml
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 5 75
Making servlets available in the Web container
1 Create the standard Web application directory structure
2 Write a servlet
3 Compile
4 Write a deployment descriptor (webxml)
5 Package all up into an archive file and name it appnamewar
6 Copy the war file into $CATALINA HOMEwebapps
7 The server detects the application and makes it available to the users
httplocalhost8080appname
There are tools developed designed to assist the programmers with theseries of tasks involved in writing Web applications
eg Ant tasks for Tomcat Eclipse Web Tools Platform (WTP)M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 6 75
How the Container handles a request ((HeadFirst) p42)
Web Server Machine
Container
Client
HTTPRequest
HttpServletRequest
HttpServletResponseContainer
Client
Servlet
Container
Client
Servlet
thread
requestresponse
Servlet
Servlet
Servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 7 75
How the Container handles a request ((HeadFirst) p42)
Container
Client
Servlet
threadrequest
response
Container
Servlet
thread
response
Container
Servlet
threadrequest
response
service()
service()
doGet()
GeneratedContent
HTTP Response
GeneratedContent
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 8 75
Your Servlet inherits rdquolifecyclerdquo methods
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()
ltltinterfacegtgtServlet
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()getInitParameter(String)getInitParameterNames()getServletContext()log(String)
GenericServlet
service(ServletRequest ServletResponse)service(HttpServletRequest HttpServletResponse)doGet(HttpServletRequest HttpServletResponse)doPost(HttpServletRequest HttpServletResponse)doHead(HttpServletRequest HttpServletResponse)doPut(HttpServletRequest HttpServletResponse)doOptions(HttpServletRequest HttpServletResponse)
HttpServlet
doGet(HttpServletRequestHttpServletResponse)myBusinessMethod()
MyServlet
javaxservletjavaxservlethttp
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 9 75
A typical Servlet looks like this
package comcomp9321
import javaio
import javaxservlet
import javaxservlethttp
public class OneServlet extends HttpServlet
public void doGet (HttpServletRequest req HttpServletResponse res)
throws ServletException IOException
ressetContentType(texthtml)
PrintWriter out = resgetWriter()
javautilDate today = new javautilDate()
outprintln(ltHTMLgtltBODYgtltH1gtOneServlet says it is now )
outprintln(today + ltH1gtltBODYgtltHTMLgt)
outclose()
Note No main() - the container calls the servlet methods like doGet() throughservice() How does the container know which servlet to call
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 10 75
Servlet Names
A servlet may have three namesI Name that the client usesI Name that used at deployment timeI Actual class name (ie OneServletclass)
All these names are declared and mapped in the deploymentdescriptor (webxml)Mapping servlet names improves your apprsquos flexibility and security
in webxml
ltweb-app xmlns=httpjavasuncomxmlnsj2ee
ltservletgt
ltservlet-namegtOneServletltservlet-namegt
ltservlet-classgtcomcomp9321OneServletltservlet-classgt
ltservletgt
ltservlet-mappinggt
ltservlet-namegtOneServletltservlet-namegt
lturl-patterngtoneservletlturl-patterngt
ltservlet-mappinggt
URL to the servlet - httplocalhost8080myApplicationoneservletM C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 11 75
A Lifecycle of a Servlet
The Web container controls the lifecycle of a servlet class
Container
Web Container Servlet Class Servlet Object
1001010000011010 10 000101
initialised
initialised
load class
Instantiate servlet
init()
service()
destroy()
handleclientrequests (doXX())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 12 75
Servletrsquos Life ((HeadFirst) p99)
lifecyclecalls
When itrsquos called What itrsquos for Overrideit
init() Container calls init() after theservlet instance is created butbefore the serlvet can serviceclientrsquos requests
Gives you a chance to ini-tialise your servlet before han-dling any requests
No
service() When the first client requestcomes in the container startsa new thread and calls ser-vice() method
This one looks at the re-quest and determines theHTTP method and invokesthe matching doXX() on theservlet
No
doXX() The service() method invokesappropriate doXX()
This is where your Servletcode begins This is themethod that is responsible forwhatever the servlet is sup-posed to be doing
Always
Maybe (eg getting a database connection) but not always
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 13 75
Why care about this initialisation details (HeadFirst) p104
Once the servlet is initialised the servlet gets access to two importantobjects
A ServletConfig object
I One ServletConfig object per servletI Use it to pass deploy-time information to the servlet (any info that
you do not want to hard-code into the servlet)I Use it to access the ServletContextI Parameters are configured in the deployment descriptor
A ServletContextI One ServletContext per Web application (they should have named it
AppContext)I Use it to access parameters that are Web application-wideI Use it as a kind of application bulletin-board where you can put up
info (called attributes) that other parts of the application can accessI Use it to get server info including the name and version of the
container etc
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 14 75
Why care about this initialisation details (HeadFirst) p104
does not exist
Servlet(initialised)
init(ServletConfig)
service()
destroy()
constructor
By the time servlet is running doXX() its got
a ServletConfigServletConfig
Servlet A Servlet B Servlet C
JSP A
ServletContext
ServletConfig
ServletConfig
ServletConfig
App-Wideparams
Servlet-Wideparams
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 15 75
ServletConfig Passing servlet configuration information
The Web container can pass some configuration information (eg initialparameters) for individual servlets in webxml
ltweb-appgtltservletgt
ltservlet-namegtDemoServletltservlet-namegtltservlet-classgtcomcomp9321ConfigDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtWebMasterltparam-namegtltparam-valuegtHelen Paikltparam-valuegt
ltinit-paramgtltinit-paramgt
ltparam-namegtWebMasterEmailltparam-namegtltparam-valuegthpaikwebmastercomltparam-valuegt
ltinit-paramgtltservletgtltservletgt
ltservlet-namegtSecondDemoServletltservlet-namegtltservlet-classgtcomcomp9321NextDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtlanguageltparam-namegtltparam-valuegtItalianltparam-valuegt
ltinit-paramgtltservletgt
ltweb-appgt
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 16 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Tomcat Web container structure
bin (starstop the server) commonlib(shared libraries Tomcat-wide)
conf (server configuration files)
webapps (Web application base directory)
The structure of a Web Application Archive(war)
simplewar
indexhtml
WEB-INF
lib
classesmyFirstServletclass
webxml
To access the Web apphttplocalhost8080simpleindexhtml
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 5 75
Making servlets available in the Web container
1 Create the standard Web application directory structure
2 Write a servlet
3 Compile
4 Write a deployment descriptor (webxml)
5 Package all up into an archive file and name it appnamewar
6 Copy the war file into $CATALINA HOMEwebapps
7 The server detects the application and makes it available to the users
httplocalhost8080appname
There are tools developed designed to assist the programmers with theseries of tasks involved in writing Web applications
eg Ant tasks for Tomcat Eclipse Web Tools Platform (WTP)M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 6 75
How the Container handles a request ((HeadFirst) p42)
Web Server Machine
Container
Client
HTTPRequest
HttpServletRequest
HttpServletResponseContainer
Client
Servlet
Container
Client
Servlet
thread
requestresponse
Servlet
Servlet
Servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 7 75
How the Container handles a request ((HeadFirst) p42)
Container
Client
Servlet
threadrequest
response
Container
Servlet
thread
response
Container
Servlet
threadrequest
response
service()
service()
doGet()
GeneratedContent
HTTP Response
GeneratedContent
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 8 75
Your Servlet inherits rdquolifecyclerdquo methods
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()
ltltinterfacegtgtServlet
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()getInitParameter(String)getInitParameterNames()getServletContext()log(String)
GenericServlet
service(ServletRequest ServletResponse)service(HttpServletRequest HttpServletResponse)doGet(HttpServletRequest HttpServletResponse)doPost(HttpServletRequest HttpServletResponse)doHead(HttpServletRequest HttpServletResponse)doPut(HttpServletRequest HttpServletResponse)doOptions(HttpServletRequest HttpServletResponse)
HttpServlet
doGet(HttpServletRequestHttpServletResponse)myBusinessMethod()
MyServlet
javaxservletjavaxservlethttp
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 9 75
A typical Servlet looks like this
package comcomp9321
import javaio
import javaxservlet
import javaxservlethttp
public class OneServlet extends HttpServlet
public void doGet (HttpServletRequest req HttpServletResponse res)
throws ServletException IOException
ressetContentType(texthtml)
PrintWriter out = resgetWriter()
javautilDate today = new javautilDate()
outprintln(ltHTMLgtltBODYgtltH1gtOneServlet says it is now )
outprintln(today + ltH1gtltBODYgtltHTMLgt)
outclose()
Note No main() - the container calls the servlet methods like doGet() throughservice() How does the container know which servlet to call
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 10 75
Servlet Names
A servlet may have three namesI Name that the client usesI Name that used at deployment timeI Actual class name (ie OneServletclass)
All these names are declared and mapped in the deploymentdescriptor (webxml)Mapping servlet names improves your apprsquos flexibility and security
in webxml
ltweb-app xmlns=httpjavasuncomxmlnsj2ee
ltservletgt
ltservlet-namegtOneServletltservlet-namegt
ltservlet-classgtcomcomp9321OneServletltservlet-classgt
ltservletgt
ltservlet-mappinggt
ltservlet-namegtOneServletltservlet-namegt
lturl-patterngtoneservletlturl-patterngt
ltservlet-mappinggt
URL to the servlet - httplocalhost8080myApplicationoneservletM C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 11 75
A Lifecycle of a Servlet
The Web container controls the lifecycle of a servlet class
Container
Web Container Servlet Class Servlet Object
1001010000011010 10 000101
initialised
initialised
load class
Instantiate servlet
init()
service()
destroy()
handleclientrequests (doXX())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 12 75
Servletrsquos Life ((HeadFirst) p99)
lifecyclecalls
When itrsquos called What itrsquos for Overrideit
init() Container calls init() after theservlet instance is created butbefore the serlvet can serviceclientrsquos requests
Gives you a chance to ini-tialise your servlet before han-dling any requests
No
service() When the first client requestcomes in the container startsa new thread and calls ser-vice() method
This one looks at the re-quest and determines theHTTP method and invokesthe matching doXX() on theservlet
No
doXX() The service() method invokesappropriate doXX()
This is where your Servletcode begins This is themethod that is responsible forwhatever the servlet is sup-posed to be doing
Always
Maybe (eg getting a database connection) but not always
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 13 75
Why care about this initialisation details (HeadFirst) p104
Once the servlet is initialised the servlet gets access to two importantobjects
A ServletConfig object
I One ServletConfig object per servletI Use it to pass deploy-time information to the servlet (any info that
you do not want to hard-code into the servlet)I Use it to access the ServletContextI Parameters are configured in the deployment descriptor
A ServletContextI One ServletContext per Web application (they should have named it
AppContext)I Use it to access parameters that are Web application-wideI Use it as a kind of application bulletin-board where you can put up
info (called attributes) that other parts of the application can accessI Use it to get server info including the name and version of the
container etc
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 14 75
Why care about this initialisation details (HeadFirst) p104
does not exist
Servlet(initialised)
init(ServletConfig)
service()
destroy()
constructor
By the time servlet is running doXX() its got
a ServletConfigServletConfig
Servlet A Servlet B Servlet C
JSP A
ServletContext
ServletConfig
ServletConfig
ServletConfig
App-Wideparams
Servlet-Wideparams
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 15 75
ServletConfig Passing servlet configuration information
The Web container can pass some configuration information (eg initialparameters) for individual servlets in webxml
ltweb-appgtltservletgt
ltservlet-namegtDemoServletltservlet-namegtltservlet-classgtcomcomp9321ConfigDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtWebMasterltparam-namegtltparam-valuegtHelen Paikltparam-valuegt
ltinit-paramgtltinit-paramgt
ltparam-namegtWebMasterEmailltparam-namegtltparam-valuegthpaikwebmastercomltparam-valuegt
ltinit-paramgtltservletgtltservletgt
ltservlet-namegtSecondDemoServletltservlet-namegtltservlet-classgtcomcomp9321NextDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtlanguageltparam-namegtltparam-valuegtItalianltparam-valuegt
ltinit-paramgtltservletgt
ltweb-appgt
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 16 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Tomcat Web container structure
bin (starstop the server) commonlib(shared libraries Tomcat-wide)
conf (server configuration files)
webapps (Web application base directory)
The structure of a Web Application Archive(war)
simplewar
indexhtml
WEB-INF
lib
classesmyFirstServletclass
webxml
To access the Web apphttplocalhost8080simpleindexhtml
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 5 75
Making servlets available in the Web container
1 Create the standard Web application directory structure
2 Write a servlet
3 Compile
4 Write a deployment descriptor (webxml)
5 Package all up into an archive file and name it appnamewar
6 Copy the war file into $CATALINA HOMEwebapps
7 The server detects the application and makes it available to the users
httplocalhost8080appname
There are tools developed designed to assist the programmers with theseries of tasks involved in writing Web applications
eg Ant tasks for Tomcat Eclipse Web Tools Platform (WTP)M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 6 75
How the Container handles a request ((HeadFirst) p42)
Web Server Machine
Container
Client
HTTPRequest
HttpServletRequest
HttpServletResponseContainer
Client
Servlet
Container
Client
Servlet
thread
requestresponse
Servlet
Servlet
Servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 7 75
How the Container handles a request ((HeadFirst) p42)
Container
Client
Servlet
threadrequest
response
Container
Servlet
thread
response
Container
Servlet
threadrequest
response
service()
service()
doGet()
GeneratedContent
HTTP Response
GeneratedContent
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 8 75
Your Servlet inherits rdquolifecyclerdquo methods
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()
ltltinterfacegtgtServlet
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()getInitParameter(String)getInitParameterNames()getServletContext()log(String)
GenericServlet
service(ServletRequest ServletResponse)service(HttpServletRequest HttpServletResponse)doGet(HttpServletRequest HttpServletResponse)doPost(HttpServletRequest HttpServletResponse)doHead(HttpServletRequest HttpServletResponse)doPut(HttpServletRequest HttpServletResponse)doOptions(HttpServletRequest HttpServletResponse)
HttpServlet
doGet(HttpServletRequestHttpServletResponse)myBusinessMethod()
MyServlet
javaxservletjavaxservlethttp
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 9 75
A typical Servlet looks like this
package comcomp9321
import javaio
import javaxservlet
import javaxservlethttp
public class OneServlet extends HttpServlet
public void doGet (HttpServletRequest req HttpServletResponse res)
throws ServletException IOException
ressetContentType(texthtml)
PrintWriter out = resgetWriter()
javautilDate today = new javautilDate()
outprintln(ltHTMLgtltBODYgtltH1gtOneServlet says it is now )
outprintln(today + ltH1gtltBODYgtltHTMLgt)
outclose()
Note No main() - the container calls the servlet methods like doGet() throughservice() How does the container know which servlet to call
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 10 75
Servlet Names
A servlet may have three namesI Name that the client usesI Name that used at deployment timeI Actual class name (ie OneServletclass)
All these names are declared and mapped in the deploymentdescriptor (webxml)Mapping servlet names improves your apprsquos flexibility and security
in webxml
ltweb-app xmlns=httpjavasuncomxmlnsj2ee
ltservletgt
ltservlet-namegtOneServletltservlet-namegt
ltservlet-classgtcomcomp9321OneServletltservlet-classgt
ltservletgt
ltservlet-mappinggt
ltservlet-namegtOneServletltservlet-namegt
lturl-patterngtoneservletlturl-patterngt
ltservlet-mappinggt
URL to the servlet - httplocalhost8080myApplicationoneservletM C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 11 75
A Lifecycle of a Servlet
The Web container controls the lifecycle of a servlet class
Container
Web Container Servlet Class Servlet Object
1001010000011010 10 000101
initialised
initialised
load class
Instantiate servlet
init()
service()
destroy()
handleclientrequests (doXX())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 12 75
Servletrsquos Life ((HeadFirst) p99)
lifecyclecalls
When itrsquos called What itrsquos for Overrideit
init() Container calls init() after theservlet instance is created butbefore the serlvet can serviceclientrsquos requests
Gives you a chance to ini-tialise your servlet before han-dling any requests
No
service() When the first client requestcomes in the container startsa new thread and calls ser-vice() method
This one looks at the re-quest and determines theHTTP method and invokesthe matching doXX() on theservlet
No
doXX() The service() method invokesappropriate doXX()
This is where your Servletcode begins This is themethod that is responsible forwhatever the servlet is sup-posed to be doing
Always
Maybe (eg getting a database connection) but not always
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 13 75
Why care about this initialisation details (HeadFirst) p104
Once the servlet is initialised the servlet gets access to two importantobjects
A ServletConfig object
I One ServletConfig object per servletI Use it to pass deploy-time information to the servlet (any info that
you do not want to hard-code into the servlet)I Use it to access the ServletContextI Parameters are configured in the deployment descriptor
A ServletContextI One ServletContext per Web application (they should have named it
AppContext)I Use it to access parameters that are Web application-wideI Use it as a kind of application bulletin-board where you can put up
info (called attributes) that other parts of the application can accessI Use it to get server info including the name and version of the
container etc
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 14 75
Why care about this initialisation details (HeadFirst) p104
does not exist
Servlet(initialised)
init(ServletConfig)
service()
destroy()
constructor
By the time servlet is running doXX() its got
a ServletConfigServletConfig
Servlet A Servlet B Servlet C
JSP A
ServletContext
ServletConfig
ServletConfig
ServletConfig
App-Wideparams
Servlet-Wideparams
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 15 75
ServletConfig Passing servlet configuration information
The Web container can pass some configuration information (eg initialparameters) for individual servlets in webxml
ltweb-appgtltservletgt
ltservlet-namegtDemoServletltservlet-namegtltservlet-classgtcomcomp9321ConfigDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtWebMasterltparam-namegtltparam-valuegtHelen Paikltparam-valuegt
ltinit-paramgtltinit-paramgt
ltparam-namegtWebMasterEmailltparam-namegtltparam-valuegthpaikwebmastercomltparam-valuegt
ltinit-paramgtltservletgtltservletgt
ltservlet-namegtSecondDemoServletltservlet-namegtltservlet-classgtcomcomp9321NextDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtlanguageltparam-namegtltparam-valuegtItalianltparam-valuegt
ltinit-paramgtltservletgt
ltweb-appgt
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 16 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Tomcat Web container structure
bin (starstop the server) commonlib(shared libraries Tomcat-wide)
conf (server configuration files)
webapps (Web application base directory)
The structure of a Web Application Archive(war)
simplewar
indexhtml
WEB-INF
lib
classesmyFirstServletclass
webxml
To access the Web apphttplocalhost8080simpleindexhtml
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 5 75
Making servlets available in the Web container
1 Create the standard Web application directory structure
2 Write a servlet
3 Compile
4 Write a deployment descriptor (webxml)
5 Package all up into an archive file and name it appnamewar
6 Copy the war file into $CATALINA HOMEwebapps
7 The server detects the application and makes it available to the users
httplocalhost8080appname
There are tools developed designed to assist the programmers with theseries of tasks involved in writing Web applications
eg Ant tasks for Tomcat Eclipse Web Tools Platform (WTP)M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 6 75
How the Container handles a request ((HeadFirst) p42)
Web Server Machine
Container
Client
HTTPRequest
HttpServletRequest
HttpServletResponseContainer
Client
Servlet
Container
Client
Servlet
thread
requestresponse
Servlet
Servlet
Servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 7 75
How the Container handles a request ((HeadFirst) p42)
Container
Client
Servlet
threadrequest
response
Container
Servlet
thread
response
Container
Servlet
threadrequest
response
service()
service()
doGet()
GeneratedContent
HTTP Response
GeneratedContent
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 8 75
Your Servlet inherits rdquolifecyclerdquo methods
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()
ltltinterfacegtgtServlet
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()getInitParameter(String)getInitParameterNames()getServletContext()log(String)
GenericServlet
service(ServletRequest ServletResponse)service(HttpServletRequest HttpServletResponse)doGet(HttpServletRequest HttpServletResponse)doPost(HttpServletRequest HttpServletResponse)doHead(HttpServletRequest HttpServletResponse)doPut(HttpServletRequest HttpServletResponse)doOptions(HttpServletRequest HttpServletResponse)
HttpServlet
doGet(HttpServletRequestHttpServletResponse)myBusinessMethod()
MyServlet
javaxservletjavaxservlethttp
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 9 75
A typical Servlet looks like this
package comcomp9321
import javaio
import javaxservlet
import javaxservlethttp
public class OneServlet extends HttpServlet
public void doGet (HttpServletRequest req HttpServletResponse res)
throws ServletException IOException
ressetContentType(texthtml)
PrintWriter out = resgetWriter()
javautilDate today = new javautilDate()
outprintln(ltHTMLgtltBODYgtltH1gtOneServlet says it is now )
outprintln(today + ltH1gtltBODYgtltHTMLgt)
outclose()
Note No main() - the container calls the servlet methods like doGet() throughservice() How does the container know which servlet to call
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 10 75
Servlet Names
A servlet may have three namesI Name that the client usesI Name that used at deployment timeI Actual class name (ie OneServletclass)
All these names are declared and mapped in the deploymentdescriptor (webxml)Mapping servlet names improves your apprsquos flexibility and security
in webxml
ltweb-app xmlns=httpjavasuncomxmlnsj2ee
ltservletgt
ltservlet-namegtOneServletltservlet-namegt
ltservlet-classgtcomcomp9321OneServletltservlet-classgt
ltservletgt
ltservlet-mappinggt
ltservlet-namegtOneServletltservlet-namegt
lturl-patterngtoneservletlturl-patterngt
ltservlet-mappinggt
URL to the servlet - httplocalhost8080myApplicationoneservletM C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 11 75
A Lifecycle of a Servlet
The Web container controls the lifecycle of a servlet class
Container
Web Container Servlet Class Servlet Object
1001010000011010 10 000101
initialised
initialised
load class
Instantiate servlet
init()
service()
destroy()
handleclientrequests (doXX())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 12 75
Servletrsquos Life ((HeadFirst) p99)
lifecyclecalls
When itrsquos called What itrsquos for Overrideit
init() Container calls init() after theservlet instance is created butbefore the serlvet can serviceclientrsquos requests
Gives you a chance to ini-tialise your servlet before han-dling any requests
No
service() When the first client requestcomes in the container startsa new thread and calls ser-vice() method
This one looks at the re-quest and determines theHTTP method and invokesthe matching doXX() on theservlet
No
doXX() The service() method invokesappropriate doXX()
This is where your Servletcode begins This is themethod that is responsible forwhatever the servlet is sup-posed to be doing
Always
Maybe (eg getting a database connection) but not always
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 13 75
Why care about this initialisation details (HeadFirst) p104
Once the servlet is initialised the servlet gets access to two importantobjects
A ServletConfig object
I One ServletConfig object per servletI Use it to pass deploy-time information to the servlet (any info that
you do not want to hard-code into the servlet)I Use it to access the ServletContextI Parameters are configured in the deployment descriptor
A ServletContextI One ServletContext per Web application (they should have named it
AppContext)I Use it to access parameters that are Web application-wideI Use it as a kind of application bulletin-board where you can put up
info (called attributes) that other parts of the application can accessI Use it to get server info including the name and version of the
container etc
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 14 75
Why care about this initialisation details (HeadFirst) p104
does not exist
Servlet(initialised)
init(ServletConfig)
service()
destroy()
constructor
By the time servlet is running doXX() its got
a ServletConfigServletConfig
Servlet A Servlet B Servlet C
JSP A
ServletContext
ServletConfig
ServletConfig
ServletConfig
App-Wideparams
Servlet-Wideparams
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 15 75
ServletConfig Passing servlet configuration information
The Web container can pass some configuration information (eg initialparameters) for individual servlets in webxml
ltweb-appgtltservletgt
ltservlet-namegtDemoServletltservlet-namegtltservlet-classgtcomcomp9321ConfigDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtWebMasterltparam-namegtltparam-valuegtHelen Paikltparam-valuegt
ltinit-paramgtltinit-paramgt
ltparam-namegtWebMasterEmailltparam-namegtltparam-valuegthpaikwebmastercomltparam-valuegt
ltinit-paramgtltservletgtltservletgt
ltservlet-namegtSecondDemoServletltservlet-namegtltservlet-classgtcomcomp9321NextDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtlanguageltparam-namegtltparam-valuegtItalianltparam-valuegt
ltinit-paramgtltservletgt
ltweb-appgt
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 16 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Tomcat Web container structure
bin (starstop the server) commonlib(shared libraries Tomcat-wide)
conf (server configuration files)
webapps (Web application base directory)
The structure of a Web Application Archive(war)
simplewar
indexhtml
WEB-INF
lib
classesmyFirstServletclass
webxml
To access the Web apphttplocalhost8080simpleindexhtml
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 5 75
Making servlets available in the Web container
1 Create the standard Web application directory structure
2 Write a servlet
3 Compile
4 Write a deployment descriptor (webxml)
5 Package all up into an archive file and name it appnamewar
6 Copy the war file into $CATALINA HOMEwebapps
7 The server detects the application and makes it available to the users
httplocalhost8080appname
There are tools developed designed to assist the programmers with theseries of tasks involved in writing Web applications
eg Ant tasks for Tomcat Eclipse Web Tools Platform (WTP)M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 6 75
How the Container handles a request ((HeadFirst) p42)
Web Server Machine
Container
Client
HTTPRequest
HttpServletRequest
HttpServletResponseContainer
Client
Servlet
Container
Client
Servlet
thread
requestresponse
Servlet
Servlet
Servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 7 75
How the Container handles a request ((HeadFirst) p42)
Container
Client
Servlet
threadrequest
response
Container
Servlet
thread
response
Container
Servlet
threadrequest
response
service()
service()
doGet()
GeneratedContent
HTTP Response
GeneratedContent
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 8 75
Your Servlet inherits rdquolifecyclerdquo methods
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()
ltltinterfacegtgtServlet
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()getInitParameter(String)getInitParameterNames()getServletContext()log(String)
GenericServlet
service(ServletRequest ServletResponse)service(HttpServletRequest HttpServletResponse)doGet(HttpServletRequest HttpServletResponse)doPost(HttpServletRequest HttpServletResponse)doHead(HttpServletRequest HttpServletResponse)doPut(HttpServletRequest HttpServletResponse)doOptions(HttpServletRequest HttpServletResponse)
HttpServlet
doGet(HttpServletRequestHttpServletResponse)myBusinessMethod()
MyServlet
javaxservletjavaxservlethttp
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 9 75
A typical Servlet looks like this
package comcomp9321
import javaio
import javaxservlet
import javaxservlethttp
public class OneServlet extends HttpServlet
public void doGet (HttpServletRequest req HttpServletResponse res)
throws ServletException IOException
ressetContentType(texthtml)
PrintWriter out = resgetWriter()
javautilDate today = new javautilDate()
outprintln(ltHTMLgtltBODYgtltH1gtOneServlet says it is now )
outprintln(today + ltH1gtltBODYgtltHTMLgt)
outclose()
Note No main() - the container calls the servlet methods like doGet() throughservice() How does the container know which servlet to call
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 10 75
Servlet Names
A servlet may have three namesI Name that the client usesI Name that used at deployment timeI Actual class name (ie OneServletclass)
All these names are declared and mapped in the deploymentdescriptor (webxml)Mapping servlet names improves your apprsquos flexibility and security
in webxml
ltweb-app xmlns=httpjavasuncomxmlnsj2ee
ltservletgt
ltservlet-namegtOneServletltservlet-namegt
ltservlet-classgtcomcomp9321OneServletltservlet-classgt
ltservletgt
ltservlet-mappinggt
ltservlet-namegtOneServletltservlet-namegt
lturl-patterngtoneservletlturl-patterngt
ltservlet-mappinggt
URL to the servlet - httplocalhost8080myApplicationoneservletM C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 11 75
A Lifecycle of a Servlet
The Web container controls the lifecycle of a servlet class
Container
Web Container Servlet Class Servlet Object
1001010000011010 10 000101
initialised
initialised
load class
Instantiate servlet
init()
service()
destroy()
handleclientrequests (doXX())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 12 75
Servletrsquos Life ((HeadFirst) p99)
lifecyclecalls
When itrsquos called What itrsquos for Overrideit
init() Container calls init() after theservlet instance is created butbefore the serlvet can serviceclientrsquos requests
Gives you a chance to ini-tialise your servlet before han-dling any requests
No
service() When the first client requestcomes in the container startsa new thread and calls ser-vice() method
This one looks at the re-quest and determines theHTTP method and invokesthe matching doXX() on theservlet
No
doXX() The service() method invokesappropriate doXX()
This is where your Servletcode begins This is themethod that is responsible forwhatever the servlet is sup-posed to be doing
Always
Maybe (eg getting a database connection) but not always
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 13 75
Why care about this initialisation details (HeadFirst) p104
Once the servlet is initialised the servlet gets access to two importantobjects
A ServletConfig object
I One ServletConfig object per servletI Use it to pass deploy-time information to the servlet (any info that
you do not want to hard-code into the servlet)I Use it to access the ServletContextI Parameters are configured in the deployment descriptor
A ServletContextI One ServletContext per Web application (they should have named it
AppContext)I Use it to access parameters that are Web application-wideI Use it as a kind of application bulletin-board where you can put up
info (called attributes) that other parts of the application can accessI Use it to get server info including the name and version of the
container etc
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 14 75
Why care about this initialisation details (HeadFirst) p104
does not exist
Servlet(initialised)
init(ServletConfig)
service()
destroy()
constructor
By the time servlet is running doXX() its got
a ServletConfigServletConfig
Servlet A Servlet B Servlet C
JSP A
ServletContext
ServletConfig
ServletConfig
ServletConfig
App-Wideparams
Servlet-Wideparams
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 15 75
ServletConfig Passing servlet configuration information
The Web container can pass some configuration information (eg initialparameters) for individual servlets in webxml
ltweb-appgtltservletgt
ltservlet-namegtDemoServletltservlet-namegtltservlet-classgtcomcomp9321ConfigDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtWebMasterltparam-namegtltparam-valuegtHelen Paikltparam-valuegt
ltinit-paramgtltinit-paramgt
ltparam-namegtWebMasterEmailltparam-namegtltparam-valuegthpaikwebmastercomltparam-valuegt
ltinit-paramgtltservletgtltservletgt
ltservlet-namegtSecondDemoServletltservlet-namegtltservlet-classgtcomcomp9321NextDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtlanguageltparam-namegtltparam-valuegtItalianltparam-valuegt
ltinit-paramgtltservletgt
ltweb-appgt
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 16 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Java Servlets
A Java technology for generating dynamic contentUsed to process HTTP request and generate HTTP responseServlets are executed by a servlet containerServlet containers are web server extensions (eg Apache Tomcat)that provide servlet functionalityhttpjavasuncomproductsservletindexjsp
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 4 75
Tomcat Web container structure
bin (starstop the server) commonlib(shared libraries Tomcat-wide)
conf (server configuration files)
webapps (Web application base directory)
The structure of a Web Application Archive(war)
simplewar
indexhtml
WEB-INF
lib
classesmyFirstServletclass
webxml
To access the Web apphttplocalhost8080simpleindexhtml
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 5 75
Making servlets available in the Web container
1 Create the standard Web application directory structure
2 Write a servlet
3 Compile
4 Write a deployment descriptor (webxml)
5 Package all up into an archive file and name it appnamewar
6 Copy the war file into $CATALINA HOMEwebapps
7 The server detects the application and makes it available to the users
httplocalhost8080appname
There are tools developed designed to assist the programmers with theseries of tasks involved in writing Web applications
eg Ant tasks for Tomcat Eclipse Web Tools Platform (WTP)M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 6 75
How the Container handles a request ((HeadFirst) p42)
Web Server Machine
Container
Client
HTTPRequest
HttpServletRequest
HttpServletResponseContainer
Client
Servlet
Container
Client
Servlet
thread
requestresponse
Servlet
Servlet
Servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 7 75
How the Container handles a request ((HeadFirst) p42)
Container
Client
Servlet
threadrequest
response
Container
Servlet
thread
response
Container
Servlet
threadrequest
response
service()
service()
doGet()
GeneratedContent
HTTP Response
GeneratedContent
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 8 75
Your Servlet inherits rdquolifecyclerdquo methods
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()
ltltinterfacegtgtServlet
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()getInitParameter(String)getInitParameterNames()getServletContext()log(String)
GenericServlet
service(ServletRequest ServletResponse)service(HttpServletRequest HttpServletResponse)doGet(HttpServletRequest HttpServletResponse)doPost(HttpServletRequest HttpServletResponse)doHead(HttpServletRequest HttpServletResponse)doPut(HttpServletRequest HttpServletResponse)doOptions(HttpServletRequest HttpServletResponse)
HttpServlet
doGet(HttpServletRequestHttpServletResponse)myBusinessMethod()
MyServlet
javaxservletjavaxservlethttp
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 9 75
A typical Servlet looks like this
package comcomp9321
import javaio
import javaxservlet
import javaxservlethttp
public class OneServlet extends HttpServlet
public void doGet (HttpServletRequest req HttpServletResponse res)
throws ServletException IOException
ressetContentType(texthtml)
PrintWriter out = resgetWriter()
javautilDate today = new javautilDate()
outprintln(ltHTMLgtltBODYgtltH1gtOneServlet says it is now )
outprintln(today + ltH1gtltBODYgtltHTMLgt)
outclose()
Note No main() - the container calls the servlet methods like doGet() throughservice() How does the container know which servlet to call
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 10 75
Servlet Names
A servlet may have three namesI Name that the client usesI Name that used at deployment timeI Actual class name (ie OneServletclass)
All these names are declared and mapped in the deploymentdescriptor (webxml)Mapping servlet names improves your apprsquos flexibility and security
in webxml
ltweb-app xmlns=httpjavasuncomxmlnsj2ee
ltservletgt
ltservlet-namegtOneServletltservlet-namegt
ltservlet-classgtcomcomp9321OneServletltservlet-classgt
ltservletgt
ltservlet-mappinggt
ltservlet-namegtOneServletltservlet-namegt
lturl-patterngtoneservletlturl-patterngt
ltservlet-mappinggt
URL to the servlet - httplocalhost8080myApplicationoneservletM C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 11 75
A Lifecycle of a Servlet
The Web container controls the lifecycle of a servlet class
Container
Web Container Servlet Class Servlet Object
1001010000011010 10 000101
initialised
initialised
load class
Instantiate servlet
init()
service()
destroy()
handleclientrequests (doXX())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 12 75
Servletrsquos Life ((HeadFirst) p99)
lifecyclecalls
When itrsquos called What itrsquos for Overrideit
init() Container calls init() after theservlet instance is created butbefore the serlvet can serviceclientrsquos requests
Gives you a chance to ini-tialise your servlet before han-dling any requests
No
service() When the first client requestcomes in the container startsa new thread and calls ser-vice() method
This one looks at the re-quest and determines theHTTP method and invokesthe matching doXX() on theservlet
No
doXX() The service() method invokesappropriate doXX()
This is where your Servletcode begins This is themethod that is responsible forwhatever the servlet is sup-posed to be doing
Always
Maybe (eg getting a database connection) but not always
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 13 75
Why care about this initialisation details (HeadFirst) p104
Once the servlet is initialised the servlet gets access to two importantobjects
A ServletConfig object
I One ServletConfig object per servletI Use it to pass deploy-time information to the servlet (any info that
you do not want to hard-code into the servlet)I Use it to access the ServletContextI Parameters are configured in the deployment descriptor
A ServletContextI One ServletContext per Web application (they should have named it
AppContext)I Use it to access parameters that are Web application-wideI Use it as a kind of application bulletin-board where you can put up
info (called attributes) that other parts of the application can accessI Use it to get server info including the name and version of the
container etc
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 14 75
Why care about this initialisation details (HeadFirst) p104
does not exist
Servlet(initialised)
init(ServletConfig)
service()
destroy()
constructor
By the time servlet is running doXX() its got
a ServletConfigServletConfig
Servlet A Servlet B Servlet C
JSP A
ServletContext
ServletConfig
ServletConfig
ServletConfig
App-Wideparams
Servlet-Wideparams
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 15 75
ServletConfig Passing servlet configuration information
The Web container can pass some configuration information (eg initialparameters) for individual servlets in webxml
ltweb-appgtltservletgt
ltservlet-namegtDemoServletltservlet-namegtltservlet-classgtcomcomp9321ConfigDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtWebMasterltparam-namegtltparam-valuegtHelen Paikltparam-valuegt
ltinit-paramgtltinit-paramgt
ltparam-namegtWebMasterEmailltparam-namegtltparam-valuegthpaikwebmastercomltparam-valuegt
ltinit-paramgtltservletgtltservletgt
ltservlet-namegtSecondDemoServletltservlet-namegtltservlet-classgtcomcomp9321NextDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtlanguageltparam-namegtltparam-valuegtItalianltparam-valuegt
ltinit-paramgtltservletgt
ltweb-appgt
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 16 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Tomcat Web container structure
bin (starstop the server) commonlib(shared libraries Tomcat-wide)
conf (server configuration files)
webapps (Web application base directory)
The structure of a Web Application Archive(war)
simplewar
indexhtml
WEB-INF
lib
classesmyFirstServletclass
webxml
To access the Web apphttplocalhost8080simpleindexhtml
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 5 75
Making servlets available in the Web container
1 Create the standard Web application directory structure
2 Write a servlet
3 Compile
4 Write a deployment descriptor (webxml)
5 Package all up into an archive file and name it appnamewar
6 Copy the war file into $CATALINA HOMEwebapps
7 The server detects the application and makes it available to the users
httplocalhost8080appname
There are tools developed designed to assist the programmers with theseries of tasks involved in writing Web applications
eg Ant tasks for Tomcat Eclipse Web Tools Platform (WTP)M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 6 75
How the Container handles a request ((HeadFirst) p42)
Web Server Machine
Container
Client
HTTPRequest
HttpServletRequest
HttpServletResponseContainer
Client
Servlet
Container
Client
Servlet
thread
requestresponse
Servlet
Servlet
Servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 7 75
How the Container handles a request ((HeadFirst) p42)
Container
Client
Servlet
threadrequest
response
Container
Servlet
thread
response
Container
Servlet
threadrequest
response
service()
service()
doGet()
GeneratedContent
HTTP Response
GeneratedContent
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 8 75
Your Servlet inherits rdquolifecyclerdquo methods
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()
ltltinterfacegtgtServlet
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()getInitParameter(String)getInitParameterNames()getServletContext()log(String)
GenericServlet
service(ServletRequest ServletResponse)service(HttpServletRequest HttpServletResponse)doGet(HttpServletRequest HttpServletResponse)doPost(HttpServletRequest HttpServletResponse)doHead(HttpServletRequest HttpServletResponse)doPut(HttpServletRequest HttpServletResponse)doOptions(HttpServletRequest HttpServletResponse)
HttpServlet
doGet(HttpServletRequestHttpServletResponse)myBusinessMethod()
MyServlet
javaxservletjavaxservlethttp
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 9 75
A typical Servlet looks like this
package comcomp9321
import javaio
import javaxservlet
import javaxservlethttp
public class OneServlet extends HttpServlet
public void doGet (HttpServletRequest req HttpServletResponse res)
throws ServletException IOException
ressetContentType(texthtml)
PrintWriter out = resgetWriter()
javautilDate today = new javautilDate()
outprintln(ltHTMLgtltBODYgtltH1gtOneServlet says it is now )
outprintln(today + ltH1gtltBODYgtltHTMLgt)
outclose()
Note No main() - the container calls the servlet methods like doGet() throughservice() How does the container know which servlet to call
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 10 75
Servlet Names
A servlet may have three namesI Name that the client usesI Name that used at deployment timeI Actual class name (ie OneServletclass)
All these names are declared and mapped in the deploymentdescriptor (webxml)Mapping servlet names improves your apprsquos flexibility and security
in webxml
ltweb-app xmlns=httpjavasuncomxmlnsj2ee
ltservletgt
ltservlet-namegtOneServletltservlet-namegt
ltservlet-classgtcomcomp9321OneServletltservlet-classgt
ltservletgt
ltservlet-mappinggt
ltservlet-namegtOneServletltservlet-namegt
lturl-patterngtoneservletlturl-patterngt
ltservlet-mappinggt
URL to the servlet - httplocalhost8080myApplicationoneservletM C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 11 75
A Lifecycle of a Servlet
The Web container controls the lifecycle of a servlet class
Container
Web Container Servlet Class Servlet Object
1001010000011010 10 000101
initialised
initialised
load class
Instantiate servlet
init()
service()
destroy()
handleclientrequests (doXX())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 12 75
Servletrsquos Life ((HeadFirst) p99)
lifecyclecalls
When itrsquos called What itrsquos for Overrideit
init() Container calls init() after theservlet instance is created butbefore the serlvet can serviceclientrsquos requests
Gives you a chance to ini-tialise your servlet before han-dling any requests
No
service() When the first client requestcomes in the container startsa new thread and calls ser-vice() method
This one looks at the re-quest and determines theHTTP method and invokesthe matching doXX() on theservlet
No
doXX() The service() method invokesappropriate doXX()
This is where your Servletcode begins This is themethod that is responsible forwhatever the servlet is sup-posed to be doing
Always
Maybe (eg getting a database connection) but not always
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 13 75
Why care about this initialisation details (HeadFirst) p104
Once the servlet is initialised the servlet gets access to two importantobjects
A ServletConfig object
I One ServletConfig object per servletI Use it to pass deploy-time information to the servlet (any info that
you do not want to hard-code into the servlet)I Use it to access the ServletContextI Parameters are configured in the deployment descriptor
A ServletContextI One ServletContext per Web application (they should have named it
AppContext)I Use it to access parameters that are Web application-wideI Use it as a kind of application bulletin-board where you can put up
info (called attributes) that other parts of the application can accessI Use it to get server info including the name and version of the
container etc
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 14 75
Why care about this initialisation details (HeadFirst) p104
does not exist
Servlet(initialised)
init(ServletConfig)
service()
destroy()
constructor
By the time servlet is running doXX() its got
a ServletConfigServletConfig
Servlet A Servlet B Servlet C
JSP A
ServletContext
ServletConfig
ServletConfig
ServletConfig
App-Wideparams
Servlet-Wideparams
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 15 75
ServletConfig Passing servlet configuration information
The Web container can pass some configuration information (eg initialparameters) for individual servlets in webxml
ltweb-appgtltservletgt
ltservlet-namegtDemoServletltservlet-namegtltservlet-classgtcomcomp9321ConfigDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtWebMasterltparam-namegtltparam-valuegtHelen Paikltparam-valuegt
ltinit-paramgtltinit-paramgt
ltparam-namegtWebMasterEmailltparam-namegtltparam-valuegthpaikwebmastercomltparam-valuegt
ltinit-paramgtltservletgtltservletgt
ltservlet-namegtSecondDemoServletltservlet-namegtltservlet-classgtcomcomp9321NextDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtlanguageltparam-namegtltparam-valuegtItalianltparam-valuegt
ltinit-paramgtltservletgt
ltweb-appgt
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 16 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Making servlets available in the Web container
1 Create the standard Web application directory structure
2 Write a servlet
3 Compile
4 Write a deployment descriptor (webxml)
5 Package all up into an archive file and name it appnamewar
6 Copy the war file into $CATALINA HOMEwebapps
7 The server detects the application and makes it available to the users
httplocalhost8080appname
There are tools developed designed to assist the programmers with theseries of tasks involved in writing Web applications
eg Ant tasks for Tomcat Eclipse Web Tools Platform (WTP)M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 6 75
How the Container handles a request ((HeadFirst) p42)
Web Server Machine
Container
Client
HTTPRequest
HttpServletRequest
HttpServletResponseContainer
Client
Servlet
Container
Client
Servlet
thread
requestresponse
Servlet
Servlet
Servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 7 75
How the Container handles a request ((HeadFirst) p42)
Container
Client
Servlet
threadrequest
response
Container
Servlet
thread
response
Container
Servlet
threadrequest
response
service()
service()
doGet()
GeneratedContent
HTTP Response
GeneratedContent
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 8 75
Your Servlet inherits rdquolifecyclerdquo methods
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()
ltltinterfacegtgtServlet
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()getInitParameter(String)getInitParameterNames()getServletContext()log(String)
GenericServlet
service(ServletRequest ServletResponse)service(HttpServletRequest HttpServletResponse)doGet(HttpServletRequest HttpServletResponse)doPost(HttpServletRequest HttpServletResponse)doHead(HttpServletRequest HttpServletResponse)doPut(HttpServletRequest HttpServletResponse)doOptions(HttpServletRequest HttpServletResponse)
HttpServlet
doGet(HttpServletRequestHttpServletResponse)myBusinessMethod()
MyServlet
javaxservletjavaxservlethttp
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 9 75
A typical Servlet looks like this
package comcomp9321
import javaio
import javaxservlet
import javaxservlethttp
public class OneServlet extends HttpServlet
public void doGet (HttpServletRequest req HttpServletResponse res)
throws ServletException IOException
ressetContentType(texthtml)
PrintWriter out = resgetWriter()
javautilDate today = new javautilDate()
outprintln(ltHTMLgtltBODYgtltH1gtOneServlet says it is now )
outprintln(today + ltH1gtltBODYgtltHTMLgt)
outclose()
Note No main() - the container calls the servlet methods like doGet() throughservice() How does the container know which servlet to call
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 10 75
Servlet Names
A servlet may have three namesI Name that the client usesI Name that used at deployment timeI Actual class name (ie OneServletclass)
All these names are declared and mapped in the deploymentdescriptor (webxml)Mapping servlet names improves your apprsquos flexibility and security
in webxml
ltweb-app xmlns=httpjavasuncomxmlnsj2ee
ltservletgt
ltservlet-namegtOneServletltservlet-namegt
ltservlet-classgtcomcomp9321OneServletltservlet-classgt
ltservletgt
ltservlet-mappinggt
ltservlet-namegtOneServletltservlet-namegt
lturl-patterngtoneservletlturl-patterngt
ltservlet-mappinggt
URL to the servlet - httplocalhost8080myApplicationoneservletM C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 11 75
A Lifecycle of a Servlet
The Web container controls the lifecycle of a servlet class
Container
Web Container Servlet Class Servlet Object
1001010000011010 10 000101
initialised
initialised
load class
Instantiate servlet
init()
service()
destroy()
handleclientrequests (doXX())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 12 75
Servletrsquos Life ((HeadFirst) p99)
lifecyclecalls
When itrsquos called What itrsquos for Overrideit
init() Container calls init() after theservlet instance is created butbefore the serlvet can serviceclientrsquos requests
Gives you a chance to ini-tialise your servlet before han-dling any requests
No
service() When the first client requestcomes in the container startsa new thread and calls ser-vice() method
This one looks at the re-quest and determines theHTTP method and invokesthe matching doXX() on theservlet
No
doXX() The service() method invokesappropriate doXX()
This is where your Servletcode begins This is themethod that is responsible forwhatever the servlet is sup-posed to be doing
Always
Maybe (eg getting a database connection) but not always
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 13 75
Why care about this initialisation details (HeadFirst) p104
Once the servlet is initialised the servlet gets access to two importantobjects
A ServletConfig object
I One ServletConfig object per servletI Use it to pass deploy-time information to the servlet (any info that
you do not want to hard-code into the servlet)I Use it to access the ServletContextI Parameters are configured in the deployment descriptor
A ServletContextI One ServletContext per Web application (they should have named it
AppContext)I Use it to access parameters that are Web application-wideI Use it as a kind of application bulletin-board where you can put up
info (called attributes) that other parts of the application can accessI Use it to get server info including the name and version of the
container etc
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 14 75
Why care about this initialisation details (HeadFirst) p104
does not exist
Servlet(initialised)
init(ServletConfig)
service()
destroy()
constructor
By the time servlet is running doXX() its got
a ServletConfigServletConfig
Servlet A Servlet B Servlet C
JSP A
ServletContext
ServletConfig
ServletConfig
ServletConfig
App-Wideparams
Servlet-Wideparams
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 15 75
ServletConfig Passing servlet configuration information
The Web container can pass some configuration information (eg initialparameters) for individual servlets in webxml
ltweb-appgtltservletgt
ltservlet-namegtDemoServletltservlet-namegtltservlet-classgtcomcomp9321ConfigDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtWebMasterltparam-namegtltparam-valuegtHelen Paikltparam-valuegt
ltinit-paramgtltinit-paramgt
ltparam-namegtWebMasterEmailltparam-namegtltparam-valuegthpaikwebmastercomltparam-valuegt
ltinit-paramgtltservletgtltservletgt
ltservlet-namegtSecondDemoServletltservlet-namegtltservlet-classgtcomcomp9321NextDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtlanguageltparam-namegtltparam-valuegtItalianltparam-valuegt
ltinit-paramgtltservletgt
ltweb-appgt
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 16 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
How the Container handles a request ((HeadFirst) p42)
Web Server Machine
Container
Client
HTTPRequest
HttpServletRequest
HttpServletResponseContainer
Client
Servlet
Container
Client
Servlet
thread
requestresponse
Servlet
Servlet
Servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 7 75
How the Container handles a request ((HeadFirst) p42)
Container
Client
Servlet
threadrequest
response
Container
Servlet
thread
response
Container
Servlet
threadrequest
response
service()
service()
doGet()
GeneratedContent
HTTP Response
GeneratedContent
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 8 75
Your Servlet inherits rdquolifecyclerdquo methods
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()
ltltinterfacegtgtServlet
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()getInitParameter(String)getInitParameterNames()getServletContext()log(String)
GenericServlet
service(ServletRequest ServletResponse)service(HttpServletRequest HttpServletResponse)doGet(HttpServletRequest HttpServletResponse)doPost(HttpServletRequest HttpServletResponse)doHead(HttpServletRequest HttpServletResponse)doPut(HttpServletRequest HttpServletResponse)doOptions(HttpServletRequest HttpServletResponse)
HttpServlet
doGet(HttpServletRequestHttpServletResponse)myBusinessMethod()
MyServlet
javaxservletjavaxservlethttp
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 9 75
A typical Servlet looks like this
package comcomp9321
import javaio
import javaxservlet
import javaxservlethttp
public class OneServlet extends HttpServlet
public void doGet (HttpServletRequest req HttpServletResponse res)
throws ServletException IOException
ressetContentType(texthtml)
PrintWriter out = resgetWriter()
javautilDate today = new javautilDate()
outprintln(ltHTMLgtltBODYgtltH1gtOneServlet says it is now )
outprintln(today + ltH1gtltBODYgtltHTMLgt)
outclose()
Note No main() - the container calls the servlet methods like doGet() throughservice() How does the container know which servlet to call
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 10 75
Servlet Names
A servlet may have three namesI Name that the client usesI Name that used at deployment timeI Actual class name (ie OneServletclass)
All these names are declared and mapped in the deploymentdescriptor (webxml)Mapping servlet names improves your apprsquos flexibility and security
in webxml
ltweb-app xmlns=httpjavasuncomxmlnsj2ee
ltservletgt
ltservlet-namegtOneServletltservlet-namegt
ltservlet-classgtcomcomp9321OneServletltservlet-classgt
ltservletgt
ltservlet-mappinggt
ltservlet-namegtOneServletltservlet-namegt
lturl-patterngtoneservletlturl-patterngt
ltservlet-mappinggt
URL to the servlet - httplocalhost8080myApplicationoneservletM C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 11 75
A Lifecycle of a Servlet
The Web container controls the lifecycle of a servlet class
Container
Web Container Servlet Class Servlet Object
1001010000011010 10 000101
initialised
initialised
load class
Instantiate servlet
init()
service()
destroy()
handleclientrequests (doXX())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 12 75
Servletrsquos Life ((HeadFirst) p99)
lifecyclecalls
When itrsquos called What itrsquos for Overrideit
init() Container calls init() after theservlet instance is created butbefore the serlvet can serviceclientrsquos requests
Gives you a chance to ini-tialise your servlet before han-dling any requests
No
service() When the first client requestcomes in the container startsa new thread and calls ser-vice() method
This one looks at the re-quest and determines theHTTP method and invokesthe matching doXX() on theservlet
No
doXX() The service() method invokesappropriate doXX()
This is where your Servletcode begins This is themethod that is responsible forwhatever the servlet is sup-posed to be doing
Always
Maybe (eg getting a database connection) but not always
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 13 75
Why care about this initialisation details (HeadFirst) p104
Once the servlet is initialised the servlet gets access to two importantobjects
A ServletConfig object
I One ServletConfig object per servletI Use it to pass deploy-time information to the servlet (any info that
you do not want to hard-code into the servlet)I Use it to access the ServletContextI Parameters are configured in the deployment descriptor
A ServletContextI One ServletContext per Web application (they should have named it
AppContext)I Use it to access parameters that are Web application-wideI Use it as a kind of application bulletin-board where you can put up
info (called attributes) that other parts of the application can accessI Use it to get server info including the name and version of the
container etc
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 14 75
Why care about this initialisation details (HeadFirst) p104
does not exist
Servlet(initialised)
init(ServletConfig)
service()
destroy()
constructor
By the time servlet is running doXX() its got
a ServletConfigServletConfig
Servlet A Servlet B Servlet C
JSP A
ServletContext
ServletConfig
ServletConfig
ServletConfig
App-Wideparams
Servlet-Wideparams
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 15 75
ServletConfig Passing servlet configuration information
The Web container can pass some configuration information (eg initialparameters) for individual servlets in webxml
ltweb-appgtltservletgt
ltservlet-namegtDemoServletltservlet-namegtltservlet-classgtcomcomp9321ConfigDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtWebMasterltparam-namegtltparam-valuegtHelen Paikltparam-valuegt
ltinit-paramgtltinit-paramgt
ltparam-namegtWebMasterEmailltparam-namegtltparam-valuegthpaikwebmastercomltparam-valuegt
ltinit-paramgtltservletgtltservletgt
ltservlet-namegtSecondDemoServletltservlet-namegtltservlet-classgtcomcomp9321NextDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtlanguageltparam-namegtltparam-valuegtItalianltparam-valuegt
ltinit-paramgtltservletgt
ltweb-appgt
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 16 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
How the Container handles a request ((HeadFirst) p42)
Container
Client
Servlet
threadrequest
response
Container
Servlet
thread
response
Container
Servlet
threadrequest
response
service()
service()
doGet()
GeneratedContent
HTTP Response
GeneratedContent
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 8 75
Your Servlet inherits rdquolifecyclerdquo methods
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()
ltltinterfacegtgtServlet
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()getInitParameter(String)getInitParameterNames()getServletContext()log(String)
GenericServlet
service(ServletRequest ServletResponse)service(HttpServletRequest HttpServletResponse)doGet(HttpServletRequest HttpServletResponse)doPost(HttpServletRequest HttpServletResponse)doHead(HttpServletRequest HttpServletResponse)doPut(HttpServletRequest HttpServletResponse)doOptions(HttpServletRequest HttpServletResponse)
HttpServlet
doGet(HttpServletRequestHttpServletResponse)myBusinessMethod()
MyServlet
javaxservletjavaxservlethttp
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 9 75
A typical Servlet looks like this
package comcomp9321
import javaio
import javaxservlet
import javaxservlethttp
public class OneServlet extends HttpServlet
public void doGet (HttpServletRequest req HttpServletResponse res)
throws ServletException IOException
ressetContentType(texthtml)
PrintWriter out = resgetWriter()
javautilDate today = new javautilDate()
outprintln(ltHTMLgtltBODYgtltH1gtOneServlet says it is now )
outprintln(today + ltH1gtltBODYgtltHTMLgt)
outclose()
Note No main() - the container calls the servlet methods like doGet() throughservice() How does the container know which servlet to call
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 10 75
Servlet Names
A servlet may have three namesI Name that the client usesI Name that used at deployment timeI Actual class name (ie OneServletclass)
All these names are declared and mapped in the deploymentdescriptor (webxml)Mapping servlet names improves your apprsquos flexibility and security
in webxml
ltweb-app xmlns=httpjavasuncomxmlnsj2ee
ltservletgt
ltservlet-namegtOneServletltservlet-namegt
ltservlet-classgtcomcomp9321OneServletltservlet-classgt
ltservletgt
ltservlet-mappinggt
ltservlet-namegtOneServletltservlet-namegt
lturl-patterngtoneservletlturl-patterngt
ltservlet-mappinggt
URL to the servlet - httplocalhost8080myApplicationoneservletM C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 11 75
A Lifecycle of a Servlet
The Web container controls the lifecycle of a servlet class
Container
Web Container Servlet Class Servlet Object
1001010000011010 10 000101
initialised
initialised
load class
Instantiate servlet
init()
service()
destroy()
handleclientrequests (doXX())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 12 75
Servletrsquos Life ((HeadFirst) p99)
lifecyclecalls
When itrsquos called What itrsquos for Overrideit
init() Container calls init() after theservlet instance is created butbefore the serlvet can serviceclientrsquos requests
Gives you a chance to ini-tialise your servlet before han-dling any requests
No
service() When the first client requestcomes in the container startsa new thread and calls ser-vice() method
This one looks at the re-quest and determines theHTTP method and invokesthe matching doXX() on theservlet
No
doXX() The service() method invokesappropriate doXX()
This is where your Servletcode begins This is themethod that is responsible forwhatever the servlet is sup-posed to be doing
Always
Maybe (eg getting a database connection) but not always
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 13 75
Why care about this initialisation details (HeadFirst) p104
Once the servlet is initialised the servlet gets access to two importantobjects
A ServletConfig object
I One ServletConfig object per servletI Use it to pass deploy-time information to the servlet (any info that
you do not want to hard-code into the servlet)I Use it to access the ServletContextI Parameters are configured in the deployment descriptor
A ServletContextI One ServletContext per Web application (they should have named it
AppContext)I Use it to access parameters that are Web application-wideI Use it as a kind of application bulletin-board where you can put up
info (called attributes) that other parts of the application can accessI Use it to get server info including the name and version of the
container etc
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 14 75
Why care about this initialisation details (HeadFirst) p104
does not exist
Servlet(initialised)
init(ServletConfig)
service()
destroy()
constructor
By the time servlet is running doXX() its got
a ServletConfigServletConfig
Servlet A Servlet B Servlet C
JSP A
ServletContext
ServletConfig
ServletConfig
ServletConfig
App-Wideparams
Servlet-Wideparams
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 15 75
ServletConfig Passing servlet configuration information
The Web container can pass some configuration information (eg initialparameters) for individual servlets in webxml
ltweb-appgtltservletgt
ltservlet-namegtDemoServletltservlet-namegtltservlet-classgtcomcomp9321ConfigDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtWebMasterltparam-namegtltparam-valuegtHelen Paikltparam-valuegt
ltinit-paramgtltinit-paramgt
ltparam-namegtWebMasterEmailltparam-namegtltparam-valuegthpaikwebmastercomltparam-valuegt
ltinit-paramgtltservletgtltservletgt
ltservlet-namegtSecondDemoServletltservlet-namegtltservlet-classgtcomcomp9321NextDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtlanguageltparam-namegtltparam-valuegtItalianltparam-valuegt
ltinit-paramgtltservletgt
ltweb-appgt
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 16 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Your Servlet inherits rdquolifecyclerdquo methods
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()
ltltinterfacegtgtServlet
service(ServletRequest ServletResponse)init(ServletConfig)destroy()getServletConfig()getServletInfo()getInitParameter(String)getInitParameterNames()getServletContext()log(String)
GenericServlet
service(ServletRequest ServletResponse)service(HttpServletRequest HttpServletResponse)doGet(HttpServletRequest HttpServletResponse)doPost(HttpServletRequest HttpServletResponse)doHead(HttpServletRequest HttpServletResponse)doPut(HttpServletRequest HttpServletResponse)doOptions(HttpServletRequest HttpServletResponse)
HttpServlet
doGet(HttpServletRequestHttpServletResponse)myBusinessMethod()
MyServlet
javaxservletjavaxservlethttp
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 9 75
A typical Servlet looks like this
package comcomp9321
import javaio
import javaxservlet
import javaxservlethttp
public class OneServlet extends HttpServlet
public void doGet (HttpServletRequest req HttpServletResponse res)
throws ServletException IOException
ressetContentType(texthtml)
PrintWriter out = resgetWriter()
javautilDate today = new javautilDate()
outprintln(ltHTMLgtltBODYgtltH1gtOneServlet says it is now )
outprintln(today + ltH1gtltBODYgtltHTMLgt)
outclose()
Note No main() - the container calls the servlet methods like doGet() throughservice() How does the container know which servlet to call
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 10 75
Servlet Names
A servlet may have three namesI Name that the client usesI Name that used at deployment timeI Actual class name (ie OneServletclass)
All these names are declared and mapped in the deploymentdescriptor (webxml)Mapping servlet names improves your apprsquos flexibility and security
in webxml
ltweb-app xmlns=httpjavasuncomxmlnsj2ee
ltservletgt
ltservlet-namegtOneServletltservlet-namegt
ltservlet-classgtcomcomp9321OneServletltservlet-classgt
ltservletgt
ltservlet-mappinggt
ltservlet-namegtOneServletltservlet-namegt
lturl-patterngtoneservletlturl-patterngt
ltservlet-mappinggt
URL to the servlet - httplocalhost8080myApplicationoneservletM C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 11 75
A Lifecycle of a Servlet
The Web container controls the lifecycle of a servlet class
Container
Web Container Servlet Class Servlet Object
1001010000011010 10 000101
initialised
initialised
load class
Instantiate servlet
init()
service()
destroy()
handleclientrequests (doXX())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 12 75
Servletrsquos Life ((HeadFirst) p99)
lifecyclecalls
When itrsquos called What itrsquos for Overrideit
init() Container calls init() after theservlet instance is created butbefore the serlvet can serviceclientrsquos requests
Gives you a chance to ini-tialise your servlet before han-dling any requests
No
service() When the first client requestcomes in the container startsa new thread and calls ser-vice() method
This one looks at the re-quest and determines theHTTP method and invokesthe matching doXX() on theservlet
No
doXX() The service() method invokesappropriate doXX()
This is where your Servletcode begins This is themethod that is responsible forwhatever the servlet is sup-posed to be doing
Always
Maybe (eg getting a database connection) but not always
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 13 75
Why care about this initialisation details (HeadFirst) p104
Once the servlet is initialised the servlet gets access to two importantobjects
A ServletConfig object
I One ServletConfig object per servletI Use it to pass deploy-time information to the servlet (any info that
you do not want to hard-code into the servlet)I Use it to access the ServletContextI Parameters are configured in the deployment descriptor
A ServletContextI One ServletContext per Web application (they should have named it
AppContext)I Use it to access parameters that are Web application-wideI Use it as a kind of application bulletin-board where you can put up
info (called attributes) that other parts of the application can accessI Use it to get server info including the name and version of the
container etc
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 14 75
Why care about this initialisation details (HeadFirst) p104
does not exist
Servlet(initialised)
init(ServletConfig)
service()
destroy()
constructor
By the time servlet is running doXX() its got
a ServletConfigServletConfig
Servlet A Servlet B Servlet C
JSP A
ServletContext
ServletConfig
ServletConfig
ServletConfig
App-Wideparams
Servlet-Wideparams
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 15 75
ServletConfig Passing servlet configuration information
The Web container can pass some configuration information (eg initialparameters) for individual servlets in webxml
ltweb-appgtltservletgt
ltservlet-namegtDemoServletltservlet-namegtltservlet-classgtcomcomp9321ConfigDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtWebMasterltparam-namegtltparam-valuegtHelen Paikltparam-valuegt
ltinit-paramgtltinit-paramgt
ltparam-namegtWebMasterEmailltparam-namegtltparam-valuegthpaikwebmastercomltparam-valuegt
ltinit-paramgtltservletgtltservletgt
ltservlet-namegtSecondDemoServletltservlet-namegtltservlet-classgtcomcomp9321NextDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtlanguageltparam-namegtltparam-valuegtItalianltparam-valuegt
ltinit-paramgtltservletgt
ltweb-appgt
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 16 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
A typical Servlet looks like this
package comcomp9321
import javaio
import javaxservlet
import javaxservlethttp
public class OneServlet extends HttpServlet
public void doGet (HttpServletRequest req HttpServletResponse res)
throws ServletException IOException
ressetContentType(texthtml)
PrintWriter out = resgetWriter()
javautilDate today = new javautilDate()
outprintln(ltHTMLgtltBODYgtltH1gtOneServlet says it is now )
outprintln(today + ltH1gtltBODYgtltHTMLgt)
outclose()
Note No main() - the container calls the servlet methods like doGet() throughservice() How does the container know which servlet to call
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 10 75
Servlet Names
A servlet may have three namesI Name that the client usesI Name that used at deployment timeI Actual class name (ie OneServletclass)
All these names are declared and mapped in the deploymentdescriptor (webxml)Mapping servlet names improves your apprsquos flexibility and security
in webxml
ltweb-app xmlns=httpjavasuncomxmlnsj2ee
ltservletgt
ltservlet-namegtOneServletltservlet-namegt
ltservlet-classgtcomcomp9321OneServletltservlet-classgt
ltservletgt
ltservlet-mappinggt
ltservlet-namegtOneServletltservlet-namegt
lturl-patterngtoneservletlturl-patterngt
ltservlet-mappinggt
URL to the servlet - httplocalhost8080myApplicationoneservletM C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 11 75
A Lifecycle of a Servlet
The Web container controls the lifecycle of a servlet class
Container
Web Container Servlet Class Servlet Object
1001010000011010 10 000101
initialised
initialised
load class
Instantiate servlet
init()
service()
destroy()
handleclientrequests (doXX())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 12 75
Servletrsquos Life ((HeadFirst) p99)
lifecyclecalls
When itrsquos called What itrsquos for Overrideit
init() Container calls init() after theservlet instance is created butbefore the serlvet can serviceclientrsquos requests
Gives you a chance to ini-tialise your servlet before han-dling any requests
No
service() When the first client requestcomes in the container startsa new thread and calls ser-vice() method
This one looks at the re-quest and determines theHTTP method and invokesthe matching doXX() on theservlet
No
doXX() The service() method invokesappropriate doXX()
This is where your Servletcode begins This is themethod that is responsible forwhatever the servlet is sup-posed to be doing
Always
Maybe (eg getting a database connection) but not always
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 13 75
Why care about this initialisation details (HeadFirst) p104
Once the servlet is initialised the servlet gets access to two importantobjects
A ServletConfig object
I One ServletConfig object per servletI Use it to pass deploy-time information to the servlet (any info that
you do not want to hard-code into the servlet)I Use it to access the ServletContextI Parameters are configured in the deployment descriptor
A ServletContextI One ServletContext per Web application (they should have named it
AppContext)I Use it to access parameters that are Web application-wideI Use it as a kind of application bulletin-board where you can put up
info (called attributes) that other parts of the application can accessI Use it to get server info including the name and version of the
container etc
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 14 75
Why care about this initialisation details (HeadFirst) p104
does not exist
Servlet(initialised)
init(ServletConfig)
service()
destroy()
constructor
By the time servlet is running doXX() its got
a ServletConfigServletConfig
Servlet A Servlet B Servlet C
JSP A
ServletContext
ServletConfig
ServletConfig
ServletConfig
App-Wideparams
Servlet-Wideparams
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 15 75
ServletConfig Passing servlet configuration information
The Web container can pass some configuration information (eg initialparameters) for individual servlets in webxml
ltweb-appgtltservletgt
ltservlet-namegtDemoServletltservlet-namegtltservlet-classgtcomcomp9321ConfigDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtWebMasterltparam-namegtltparam-valuegtHelen Paikltparam-valuegt
ltinit-paramgtltinit-paramgt
ltparam-namegtWebMasterEmailltparam-namegtltparam-valuegthpaikwebmastercomltparam-valuegt
ltinit-paramgtltservletgtltservletgt
ltservlet-namegtSecondDemoServletltservlet-namegtltservlet-classgtcomcomp9321NextDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtlanguageltparam-namegtltparam-valuegtItalianltparam-valuegt
ltinit-paramgtltservletgt
ltweb-appgt
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 16 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Servlet Names
A servlet may have three namesI Name that the client usesI Name that used at deployment timeI Actual class name (ie OneServletclass)
All these names are declared and mapped in the deploymentdescriptor (webxml)Mapping servlet names improves your apprsquos flexibility and security
in webxml
ltweb-app xmlns=httpjavasuncomxmlnsj2ee
ltservletgt
ltservlet-namegtOneServletltservlet-namegt
ltservlet-classgtcomcomp9321OneServletltservlet-classgt
ltservletgt
ltservlet-mappinggt
ltservlet-namegtOneServletltservlet-namegt
lturl-patterngtoneservletlturl-patterngt
ltservlet-mappinggt
URL to the servlet - httplocalhost8080myApplicationoneservletM C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 11 75
A Lifecycle of a Servlet
The Web container controls the lifecycle of a servlet class
Container
Web Container Servlet Class Servlet Object
1001010000011010 10 000101
initialised
initialised
load class
Instantiate servlet
init()
service()
destroy()
handleclientrequests (doXX())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 12 75
Servletrsquos Life ((HeadFirst) p99)
lifecyclecalls
When itrsquos called What itrsquos for Overrideit
init() Container calls init() after theservlet instance is created butbefore the serlvet can serviceclientrsquos requests
Gives you a chance to ini-tialise your servlet before han-dling any requests
No
service() When the first client requestcomes in the container startsa new thread and calls ser-vice() method
This one looks at the re-quest and determines theHTTP method and invokesthe matching doXX() on theservlet
No
doXX() The service() method invokesappropriate doXX()
This is where your Servletcode begins This is themethod that is responsible forwhatever the servlet is sup-posed to be doing
Always
Maybe (eg getting a database connection) but not always
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 13 75
Why care about this initialisation details (HeadFirst) p104
Once the servlet is initialised the servlet gets access to two importantobjects
A ServletConfig object
I One ServletConfig object per servletI Use it to pass deploy-time information to the servlet (any info that
you do not want to hard-code into the servlet)I Use it to access the ServletContextI Parameters are configured in the deployment descriptor
A ServletContextI One ServletContext per Web application (they should have named it
AppContext)I Use it to access parameters that are Web application-wideI Use it as a kind of application bulletin-board where you can put up
info (called attributes) that other parts of the application can accessI Use it to get server info including the name and version of the
container etc
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 14 75
Why care about this initialisation details (HeadFirst) p104
does not exist
Servlet(initialised)
init(ServletConfig)
service()
destroy()
constructor
By the time servlet is running doXX() its got
a ServletConfigServletConfig
Servlet A Servlet B Servlet C
JSP A
ServletContext
ServletConfig
ServletConfig
ServletConfig
App-Wideparams
Servlet-Wideparams
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 15 75
ServletConfig Passing servlet configuration information
The Web container can pass some configuration information (eg initialparameters) for individual servlets in webxml
ltweb-appgtltservletgt
ltservlet-namegtDemoServletltservlet-namegtltservlet-classgtcomcomp9321ConfigDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtWebMasterltparam-namegtltparam-valuegtHelen Paikltparam-valuegt
ltinit-paramgtltinit-paramgt
ltparam-namegtWebMasterEmailltparam-namegtltparam-valuegthpaikwebmastercomltparam-valuegt
ltinit-paramgtltservletgtltservletgt
ltservlet-namegtSecondDemoServletltservlet-namegtltservlet-classgtcomcomp9321NextDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtlanguageltparam-namegtltparam-valuegtItalianltparam-valuegt
ltinit-paramgtltservletgt
ltweb-appgt
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 16 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
A Lifecycle of a Servlet
The Web container controls the lifecycle of a servlet class
Container
Web Container Servlet Class Servlet Object
1001010000011010 10 000101
initialised
initialised
load class
Instantiate servlet
init()
service()
destroy()
handleclientrequests (doXX())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 12 75
Servletrsquos Life ((HeadFirst) p99)
lifecyclecalls
When itrsquos called What itrsquos for Overrideit
init() Container calls init() after theservlet instance is created butbefore the serlvet can serviceclientrsquos requests
Gives you a chance to ini-tialise your servlet before han-dling any requests
No
service() When the first client requestcomes in the container startsa new thread and calls ser-vice() method
This one looks at the re-quest and determines theHTTP method and invokesthe matching doXX() on theservlet
No
doXX() The service() method invokesappropriate doXX()
This is where your Servletcode begins This is themethod that is responsible forwhatever the servlet is sup-posed to be doing
Always
Maybe (eg getting a database connection) but not always
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 13 75
Why care about this initialisation details (HeadFirst) p104
Once the servlet is initialised the servlet gets access to two importantobjects
A ServletConfig object
I One ServletConfig object per servletI Use it to pass deploy-time information to the servlet (any info that
you do not want to hard-code into the servlet)I Use it to access the ServletContextI Parameters are configured in the deployment descriptor
A ServletContextI One ServletContext per Web application (they should have named it
AppContext)I Use it to access parameters that are Web application-wideI Use it as a kind of application bulletin-board where you can put up
info (called attributes) that other parts of the application can accessI Use it to get server info including the name and version of the
container etc
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 14 75
Why care about this initialisation details (HeadFirst) p104
does not exist
Servlet(initialised)
init(ServletConfig)
service()
destroy()
constructor
By the time servlet is running doXX() its got
a ServletConfigServletConfig
Servlet A Servlet B Servlet C
JSP A
ServletContext
ServletConfig
ServletConfig
ServletConfig
App-Wideparams
Servlet-Wideparams
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 15 75
ServletConfig Passing servlet configuration information
The Web container can pass some configuration information (eg initialparameters) for individual servlets in webxml
ltweb-appgtltservletgt
ltservlet-namegtDemoServletltservlet-namegtltservlet-classgtcomcomp9321ConfigDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtWebMasterltparam-namegtltparam-valuegtHelen Paikltparam-valuegt
ltinit-paramgtltinit-paramgt
ltparam-namegtWebMasterEmailltparam-namegtltparam-valuegthpaikwebmastercomltparam-valuegt
ltinit-paramgtltservletgtltservletgt
ltservlet-namegtSecondDemoServletltservlet-namegtltservlet-classgtcomcomp9321NextDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtlanguageltparam-namegtltparam-valuegtItalianltparam-valuegt
ltinit-paramgtltservletgt
ltweb-appgt
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 16 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Servletrsquos Life ((HeadFirst) p99)
lifecyclecalls
When itrsquos called What itrsquos for Overrideit
init() Container calls init() after theservlet instance is created butbefore the serlvet can serviceclientrsquos requests
Gives you a chance to ini-tialise your servlet before han-dling any requests
No
service() When the first client requestcomes in the container startsa new thread and calls ser-vice() method
This one looks at the re-quest and determines theHTTP method and invokesthe matching doXX() on theservlet
No
doXX() The service() method invokesappropriate doXX()
This is where your Servletcode begins This is themethod that is responsible forwhatever the servlet is sup-posed to be doing
Always
Maybe (eg getting a database connection) but not always
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 13 75
Why care about this initialisation details (HeadFirst) p104
Once the servlet is initialised the servlet gets access to two importantobjects
A ServletConfig object
I One ServletConfig object per servletI Use it to pass deploy-time information to the servlet (any info that
you do not want to hard-code into the servlet)I Use it to access the ServletContextI Parameters are configured in the deployment descriptor
A ServletContextI One ServletContext per Web application (they should have named it
AppContext)I Use it to access parameters that are Web application-wideI Use it as a kind of application bulletin-board where you can put up
info (called attributes) that other parts of the application can accessI Use it to get server info including the name and version of the
container etc
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 14 75
Why care about this initialisation details (HeadFirst) p104
does not exist
Servlet(initialised)
init(ServletConfig)
service()
destroy()
constructor
By the time servlet is running doXX() its got
a ServletConfigServletConfig
Servlet A Servlet B Servlet C
JSP A
ServletContext
ServletConfig
ServletConfig
ServletConfig
App-Wideparams
Servlet-Wideparams
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 15 75
ServletConfig Passing servlet configuration information
The Web container can pass some configuration information (eg initialparameters) for individual servlets in webxml
ltweb-appgtltservletgt
ltservlet-namegtDemoServletltservlet-namegtltservlet-classgtcomcomp9321ConfigDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtWebMasterltparam-namegtltparam-valuegtHelen Paikltparam-valuegt
ltinit-paramgtltinit-paramgt
ltparam-namegtWebMasterEmailltparam-namegtltparam-valuegthpaikwebmastercomltparam-valuegt
ltinit-paramgtltservletgtltservletgt
ltservlet-namegtSecondDemoServletltservlet-namegtltservlet-classgtcomcomp9321NextDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtlanguageltparam-namegtltparam-valuegtItalianltparam-valuegt
ltinit-paramgtltservletgt
ltweb-appgt
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 16 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Why care about this initialisation details (HeadFirst) p104
Once the servlet is initialised the servlet gets access to two importantobjects
A ServletConfig object
I One ServletConfig object per servletI Use it to pass deploy-time information to the servlet (any info that
you do not want to hard-code into the servlet)I Use it to access the ServletContextI Parameters are configured in the deployment descriptor
A ServletContextI One ServletContext per Web application (they should have named it
AppContext)I Use it to access parameters that are Web application-wideI Use it as a kind of application bulletin-board where you can put up
info (called attributes) that other parts of the application can accessI Use it to get server info including the name and version of the
container etc
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 14 75
Why care about this initialisation details (HeadFirst) p104
does not exist
Servlet(initialised)
init(ServletConfig)
service()
destroy()
constructor
By the time servlet is running doXX() its got
a ServletConfigServletConfig
Servlet A Servlet B Servlet C
JSP A
ServletContext
ServletConfig
ServletConfig
ServletConfig
App-Wideparams
Servlet-Wideparams
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 15 75
ServletConfig Passing servlet configuration information
The Web container can pass some configuration information (eg initialparameters) for individual servlets in webxml
ltweb-appgtltservletgt
ltservlet-namegtDemoServletltservlet-namegtltservlet-classgtcomcomp9321ConfigDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtWebMasterltparam-namegtltparam-valuegtHelen Paikltparam-valuegt
ltinit-paramgtltinit-paramgt
ltparam-namegtWebMasterEmailltparam-namegtltparam-valuegthpaikwebmastercomltparam-valuegt
ltinit-paramgtltservletgtltservletgt
ltservlet-namegtSecondDemoServletltservlet-namegtltservlet-classgtcomcomp9321NextDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtlanguageltparam-namegtltparam-valuegtItalianltparam-valuegt
ltinit-paramgtltservletgt
ltweb-appgt
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 16 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Why care about this initialisation details (HeadFirst) p104
does not exist
Servlet(initialised)
init(ServletConfig)
service()
destroy()
constructor
By the time servlet is running doXX() its got
a ServletConfigServletConfig
Servlet A Servlet B Servlet C
JSP A
ServletContext
ServletConfig
ServletConfig
ServletConfig
App-Wideparams
Servlet-Wideparams
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 15 75
ServletConfig Passing servlet configuration information
The Web container can pass some configuration information (eg initialparameters) for individual servlets in webxml
ltweb-appgtltservletgt
ltservlet-namegtDemoServletltservlet-namegtltservlet-classgtcomcomp9321ConfigDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtWebMasterltparam-namegtltparam-valuegtHelen Paikltparam-valuegt
ltinit-paramgtltinit-paramgt
ltparam-namegtWebMasterEmailltparam-namegtltparam-valuegthpaikwebmastercomltparam-valuegt
ltinit-paramgtltservletgtltservletgt
ltservlet-namegtSecondDemoServletltservlet-namegtltservlet-classgtcomcomp9321NextDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtlanguageltparam-namegtltparam-valuegtItalianltparam-valuegt
ltinit-paramgtltservletgt
ltweb-appgt
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 16 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
ServletConfig Passing servlet configuration information
The Web container can pass some configuration information (eg initialparameters) for individual servlets in webxml
ltweb-appgtltservletgt
ltservlet-namegtDemoServletltservlet-namegtltservlet-classgtcomcomp9321ConfigDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtWebMasterltparam-namegtltparam-valuegtHelen Paikltparam-valuegt
ltinit-paramgtltinit-paramgt
ltparam-namegtWebMasterEmailltparam-namegtltparam-valuegthpaikwebmastercomltparam-valuegt
ltinit-paramgtltservletgtltservletgt
ltservlet-namegtSecondDemoServletltservlet-namegtltservlet-classgtcomcomp9321NextDemoServletltservlet-classgtltinit-paramgt
ltparam-namegtlanguageltparam-namegtltparam-valuegtItalianltparam-valuegt
ltinit-paramgtltservletgt
ltweb-appgt
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 16 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Whorsquos responsible for what
Container or Servlet
Creates the request and response objects
Calls the service() method
Adds HTML content to the response object
Has a name that matches the ltservlet-classgt element in the DD
Has a reference to the response objects
Finds the URLs in the DD
Starts a new thread to handle requests
Setting the content type of the response
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 22 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
The difference between GET and POST
GET myappselectBeerTastedocolour=darkamptaste=malty HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
POST myappselectBeerTastedo HTTP11HOSTwwwcseunsweduauUser-Agent Mozilla50 (Macintosh U PPC Mac OS X Mach-O en-USAccept textxml applicationxml applicationxhtml+xml texthtml videox-mng imagepngAccept-Language en-usConnection Keep-alive
colour=darkamptaste=malty
New Empty LineBODY (payload)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 23 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
The difference between GET and POST
Sensitive data should NOT be used with GETI GETrsquos parameter data shows up in the browserrsquos input bar
POST cannot be bookmarkedI If you want to let users specify search parameters and save it for later
cannot use POST
GET is supposed to be used for getting things - information retrievalPOST is supposed to be used for sending data to be processed -update or change something on the server
Servlet
ServletDB
POST
GET
Servlet uses the POST datato update the database
Sends back a responsewith a generated HTML page
Sends back a responsewith a generated HTML page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 24 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
What determines whether the browser sends GETPOST
POST
ltA HREF=httpwwwcseunsweduaumyappindexhtmlgtclick hereltAgt
GET
ltform method=POST action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
ltform action=SelectBeerdogtSelect Beerltpgtltoptiongtlightltoptiongtamberltoptiongtdarkltselectgtltcentergtltinput type=Submitgtltcentergtltformgt
GET
What if I want to supportboth GET and POST
public void doPost( ) throws doGet(request response)
(HeadFirst) p117
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 25 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
ServletRequest amp ServletResponse Interfaces
getAttribute(String)getContentLength()getParameterNames()getParameter() Many more methods
ltltinterfacegtgtjavaxservletServletRequest
getContextPath()getCookies()getHeader(String)getQueryString()getSession()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletRequest
getButfferSize()setContentType()getWriter() Many more methods
ltltinterfacegtgtServletResponse
addCookies()addHeader()encodeRedirectURL()sendError()Many more methods
ltltinterfacegtgtjavaxservlethttpHttpServletResponse
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is calledthe service() passes two objects that implements the two to your servlet
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 26 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
HttpServletRequest HttpServletResponse
The service() method invokes appropriate doXXX() method when theservlet receives an HTTP request
Typically your (http) servlet code would have the following structure
import javaio
import javaxservlet
import javaxservlethttp
public class MyServlet extends HttpServlet public void doGet(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
public void doPost(HttpServletRequest req HttpServletResponse res)
throws IOException ServletException your code to generate response
HTTP request method determines whether doGet() or doPost() runs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 27 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
A simple servlet that generates a text messageimport javaio
import javaxservlet
import javaxservlethttp
public class StaticServlet extends HttpServlet
public void doGet(HttpServletRequest request
HttpServletResponse response)
throws IOException ServletException
responsesetContentType(texthtml)
PrintWriter out = responsegetWriter()
outprintln(ltHTMLgt)
outprintln(ltBODYgt)
outprintln(ltHEADgt)
outprintln(ltTITLEgtStatic ServletltTITLEgt)
outprintln(ltHEADgt)
outprintln(ltbodygt)
outprintln(ltCENTERgtltH1gtHello folksltH1gtltCENTERgt)
outprintln(ltBODYgt)
outprintln(ltHTMLgt)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 28 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
When you do not want to process the response yourself
if (worksForMe) handle the request
else responsesendRedirect(httpwwwcseunsweduaumyappnewServlet)
Redirection (sendRedirect())
Type in a URL
RedirectServlet
The servlet decidesthat the request should go
to a different URL
The servlet callssendRedirect(aString) on the
response
new URL(status code 301
and location)
Sends requestfor the new URL Another
Servlet
final response
(HeadFirst) p134-136
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 35 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Request Dispatching
You may want to
include the output from another servlet
delegate (forward) the request processing to another servlet
include a static HTML content
You can use methods in the RequestDispatcher interface
include to include content from another resource
public void include(HttpServletRequest req HttpServletResponse res)
forward forward a request to another servlet
public void forward(HttpServletRequest req HttpServletResponse res)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 36 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Forwarding a request to another servlet
Using include()
The called servlet can only alter the body of the response and notthe headers
The path information of the request also continues to reflect theoriginal request location
Using forward()
no content may have been committed to the client (eg flushBuffer())
the called servlet can adjust the headers as well as the body of theresponse (content produced up to the forward call is cleared from thebuffer)
The path information of the request is altered to reflect the locationof the called servlet and no further output can occur after returningfrom a forward call (the output is committed upon returning from thecall)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 41 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Attributes and Sharing Attributes
An attribute is an object bound to one of the following objects
I ServletContext (web-app wide object)I HttpServletRequestI HttpSession
an attribute is simply a namevalue pair - name is a String andattribute is an Object
Think of it an object pinned onto a board Somebody sticks it on theboard so that others can get it
Bulletin Board
Attributes
CustomerHelen
CourseCOMP9321
ChoiceDarkColour
Servlet A
Servlet B
Servlet C
Servlet D
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 44 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Who has access to the board and how long does it live
Context AttributesAdminEmail
xxxxxx
ConcurrentUsers42
ServletDB
Connection
Servlet JSPread
read
write
read
read
Everyone in the application has access
Session Attributes
UserNameHelen
ShoppingCart A
Servlet
Servlet
JSPreadwriteread
Accessible to only those with access to a specific HttpSession
Request Attributes
OptionChoiceDark Beer
Servlet JSPreadwrite
Accessible to only those with access to a specific (Http)ServletRequest
(HeadFirst p187)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 45 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Attributes API (HeadFirst p 189)
getInitParameters(String)getInitParameterNames()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
getMajorVersion()getServletInfo()
Many more methods
ltltinterfacegtgtServletContext
getContextType()getParameter()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtServletRequest
Nothing related to attributes here
ltltinterfacegtgtHttpServletRequest
setMaxInactiveInterval()getLastAccessedTime()
getAttribute(String)setAttribute(String Object)removeAttribute(String)getAttributeNames()
Many more methods
ltltinterfacegtgtHttpSession
Context
Request
Session
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 46 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Attributes are not parameters (HeadFirst p 186)
Attributes ParametersTypes
Context (Web App)RequestSession
context init paramsrequest paramsservlet init params
Method to set setAttribute(String nameObject value)
In DD and via client input
Return type Object StringMethod to get getAttribute(String name) getInitParameters(String
name)
no such thing as Session parameters
Object returned from getAttribute() has to be casted
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 47 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Request attributes and Request dispatching
We use request attributes when you want some other component of theapplication take over all or part of your request
code in doGet()
String postcode = getPostcode(requestparameter(suburb)
requestsetAttribute(pc postcode)
RequestDispatcher view =
requestgetRequestDispatcher(DisplayPostcodejsp)
viewforward(request response)
the JSP will use the attribute pc to access the postcode
There is no reason to use context or session attributes since it only appliesto this request (so request scope is enough)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 48 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Managing the user state
In most web applications
The user needs to have continuous one-on-one interactions with theapplication The user builds up ldquodatardquo which may have to be sharedacross multiple pages in the application
eg Think of a shopping cart or a flight booking
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 49 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Managing the user state
A problem in HTTP requestresponse
Web applications need to maintain a user + hisher data
HTTP is a stateless protocol
I A single requestresponse
I Nothing is remembered rsquobetween requestsrsquo from the same user
It is a programmerrsquos responsibility
The term ldquosessionrdquo is used to represent the data associated with oneuser while she navigates around a Web applicaiton
A web application may concurrently host several sessions (iemultiple users)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 50 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Session Management
Thread c
(HeadFirst) p226
Web container
BeerServlet
Thread a
Datafor
DianeRequest to
recommend a Dark BeersetAttribute()
StoresDark Beer for Diane
request 1
request 2
responseWhat price range
responseWhat price range
Web container
Thread b
Datafor
DianeSelects Expensive
responseGuiness
responseGuiness
Diane
BeerServlet
request 1
Request torecommend a Wheat Beer
Datafor TerriDiane
Terri
responseWhat price range
responseWhat price range
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 51 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
How does the container know who the client is
The client needs a unique Session ID
Web container
ID4123Sessionrequest dark
setAttribute()Stores
Dark Beer for Diane
request 1
request 2
response ID4123
Web container
ID4123Sessionrequest Expensive ID4123
response ID4123
Diane
request 1
request wheat
Diane
Terri
new - generate an ID
new - generate ID
requestID4123
HttpServletRequest
existing ID
ID5555Session
setAttribute()Stores
Wheat Beer for Terri
response ID5555
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 52 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Session Management
There are a number of ways to deal with sessionsThe basic idea
When a user request comes in besides sending the response thecontainer also sends an identifier
the identifier is recorded by the server
When the container receives a request with the same identifier it cantreat the request as belonging to the same user
There are four techniques available
Without the containerrsquos helpI URL rewritingI HTML hidden fieldsI Cookies
With the containerrsquos helpI HTTP Session objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 53 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
URL Rewriting
In this method you append a token or identifier of the session to the URLof the next servlet (or resource)
httpmyserverportCOMP9321nextservletuserId=22987600
(inside nextservlet)
requestgetParameter(userId)
You need to consider several things
URL cannot be longer than 2000 characters
Special characters such as amp or spaces should be encoded
The values you pass can be seen in the URL
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 54 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
HTML hidden fields
A token or identifier is passed as the value for an HTML hidden field in aform
ltFORM METHOD=POST ACTION=nextservletlgt
ltINPUT TYPE=hidden NAME=token VALUE=990088gt
ltINPUT TYPE=hidden NAME=allowed VALUE=truegt
ltINPUT TYPE=submit NAME=Continuegt
(inside nextservlet)
requestgetParameter(token)
requestgetParameter(allowed)
URL cannot be seen by the user
but you still can read them from viewing the HTML source
an HTML form is always required in every page
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 55 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
CookiesA cookie is a small data item that was introduced to maintain HTTPstate by Netscape around 1994
A cookie is created by the server and sent to a browser inside aheader It is subsequently used by the server
The browser does not interpret cookies
Cookies are kept in the browserrsquos memory or can be written to a filefor future references
Eg Inside a cookie file
Set-Cookie username=joe path= domain=wwwcomp9321com
expires=2003-06-01 000000GMT version=0
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 56 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Cookies
In servlet programming a cookie is represented by the Cookie class inthe javaxservlethttp package
Cookie c1 = new Cookie(myCookie secret)
You then can add the cookie to the HTTP response using theaddCookie method of the HttpServletResponse interface
responseaddCookie(c1)
Note that because cookies are carried in the request and responseheaders you must not add a cookie after an output has been writtento the HttpServletResponse object
setDomain() getDomain() setMaxAge()
getMaxAge() setPath() getPath()
getName() setValue()
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 57 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
HTTP Sessions with JSESSIONID cookie
The most convenient way of managing sessions is through the Sessionobject represented by the javaxservlethttpHttpSession interface
For each user the container creates an HttpSession object to beassociated with that user
The HttpSession object acts like a Hashtable into which you can storeany number of keyobject pairs (called HttpSession Attributes)
An HttpSession object relies on a cookie or URL rewriting to send atoken to the client
The token is usually a unique number called the session identifier(JSESSIONID) This session identifier is used to associate a user witha Session object in the server
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 60 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
HTTP Sessions Interface
Web container
HTTP11 200 OKSet-Cookie JSESSIONID=0AAB6C8DE415Content-Type texthtmlContent-Lengh 397Date Wed 19 Nov 2005 032540 GMTServer Apache 11Connection closelthtmlgtlthtmlgt
Request
SetCookie
Web container
POST selectBeerPriceRange HTTP11Host wwwcseunsweduauUser-Agent Mozilla 50Cookie JSESSION=0AAB6C8DE415Accept nextxmlapplicationxmlapplicationxhtmlAccept-Language en-us
NextRequest
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 61 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
An example of using HttpSession object the scenarioIssue
Welcome
StartSession
DisplayChoices
Add Choiceto Journey
Show Journeyso far
CloseSession
WelcomeServlet
Createa Journey object
for the user
MenuServlet
ControlServlet
EnoughServlet
More Yes
No
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 62 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
The Journey Object
In a Journey object a record of the userrsquos proposed travel destinations ismaintained
import javautil
import javaioSerializable
public class Journey implements Serializable
private Vector Places
public Journey() Places = new Vector()
public Iterator getPlaces() return thisPlacesiterator()
public boolean addPlace(String place) return Placesadd(place)
public String toString() return Journey to
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 63 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Using a Journey Object
The following segment of code
1 initialises a new Journey object
2 adds VIC then NSW then QLD to the journey
3 then (iii) print out the all the places on the route
Journey jny = new Journey()
jnyaddPlace(VIC)
jnyaddPlace(NSW)
jnyaddPlace(QLD)
Iterator i = jnygetPlaces()
while (ihasNext())
Systemoutprintln(- + inext())
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 64 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
How session tracking works User Travel-Application
WelcomeServlet
MenuServlet
ControlServlet
EnoughServlet
requestresponse
requestresponse (sessID=50)
request (sessID=50)response (sessID=50)
request (sessID=50)response
SessionTables25s29s36s50
(In the servlet container)
new entry for the new user
SessionData
s25s29s36
JourneyFlagQueuePatron
s50 JourneyFlag
id attribute address
SAWA
jny obj
Memory
jny2 obj
user1user2user3user4
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 69 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
When Cookie is disabled by the client
The container uses URL rewriting as a fall back method
public class MenuServlet extends HttpServlet
public void doPost (HttpServletRequest req
HttpServletResponse res)
throws ServletException IOException ressetContentType(texthtml)
PrintWriter out = resgetWriter()
HttpSession session = reqgetSession()
outprintln(ltHTMLgtltBODYgt)
outprintln(ltA HREF= + responseencodeURL(ControlerServlet)
+ gtNext PageltAgt)
outprintln(ltBODYgtltHTMLgt)
encodeURL() adds the extra sessionID info to the given URL
(eg http ControlerServletJSESSIONID=AJKN88809)
you need to use encodeURL for all URLs
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 73 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Getting rid of Sessions
Three ways a session can die
It times out
You can call invalidate() on the session object
The application goes down (eg crashed or undeployed)
Configuring session timeout in DD (in minutes)
ltweb-app gt
ltservletgt
ltservletgt
ltsession-configgt
ltsession-timeoutgt15ltsession-timeoutgt
ltsession-configgt
ltweb-appgt
Setting session timeout for a specific session (in seconds)
sessionsetMaxInactiveInterval(2060)
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 74 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Servlets
WebBrowser
ltFORMgtltINPUTgtparametersltINPUTgtltFORMgt
Web Server
ServletContainer
Servletclasses
DB
HTTP Request(URL + data)
HTTP ResponseHTML (+javascript)
request
response(contentproducedfrom servlet)
Is Java-based technology for generating dynamic HTTP content
A servlet lifecycle is managed by Servlet Container
Follows the requestresponse paradigm
Implements methods (eg doGet()) to process HTTP requests
Session tracking using HttpSession objects
M C Barukh H Paik (CSE UNSW) COMP9321 14s2 Week 2 75 75
Top Related