SlideShare une entreprise Scribd logo
1  sur  115
CSI3140
WWW Structures, Techniques, and Standards

Chapter 6
Server-side Programming:
Java Servlets

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Server-side Programming
• The combination of
– HTML
– JavaScript
– DOM
is sometimes referred to as Dynamic HTML
(DHTML)

• Web pages that include scripting are often
called dynamic pages (vs. static)
Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Server-side Programming
• Similarly, web server response can be
static or dynamic
– Static: HTML document is retrieved from the
file system and returned to the client
– Dynamic: HTML document is generated by a
program in response to an HTTP request

• Java servlets are one technology for
producing dynamic server responses
– Servlet is a Java class instantiated by the
server to produce a dynamic response
Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Servlet Overview

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Servlet Overview
1. When server starts, it instantiates servlets
2. Server receives HTTP request, determines
need for dynamic response
3. Server selects the appropriate servlet to
generate the response, creates
request/response objects, and passes them to
a method on the servlet instance
4. Servlet adds information to response object via
method calls
5. Server generates HTTP response based on
information stored in response object
Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Hello World! Servlet

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Hello World! Servlet
All servlets we will write
are subclasses of
HttpServlet

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Hello World! Servlet

Server calls doGet() in response to GET request

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Hello World! Servlet

Interfaces implemented by request/response objects

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Hello World! Servlet

Production servlet should
catch these exceptions

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Hello World! Servlet
• JWSDP Tomcat server exception handling:
– Writing a trace for the exception in
logs/jwsdp_log.*.txt log file
– Returning HTML page to client that may (or may not)
contain partial exception trace

• If servlet prints a stack trace itself by calling
printStackTrace(), or if it writes debugging
output to System.out or System.err, this
output will be appended to the file
logs/launcher.server.log
Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Hello World! Servlet

First two
things done
by typical servlet;
must be in this
order

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Hello World! Servlet

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Hello World! Servlet

HTML generated by calling print() or
println() on the servlet’s
PrintWriter object

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Hello World! Servlet

Good practice to explicitly close
the PrintWriter when done

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Servlets vs. Java Applications
• Servlets do not have a main()
– The main() is in the server
– Entry point to servlet code is via call to a
method (doGet() in the example)

• Servlet interaction with end user is indirect
via request/response object APIs
– Actual HTTP request/response processing is
handled by the server

• Primary servlet output is typically HTML
Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Running Servlets
•

Simple way to run a servlet (better later):
1. Compile servlet (make sure that JWSDP
libraries are on path)
2. Copy .class file to shared/classes
directory
3. (Re)start the Tomcat web server
4. If the class is named ServletHello,
browse to
http://localhost:8080/servlet/ServletHello

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Dynamic Content

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Dynamic Content

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Dynamic Content

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Dynamic Content
• Potential problems:
– Assuming one instance of servlet on one
server, but
• Many Web sites are distributed over multiple
servers
• Even a single server can (not default) create
multiple instances of a single servlet

– Even if the assumption is correct, this servlet
does not handle concurrent accesses properly
• We’ll deal with this later in the chapter
Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Servlet Life Cycle
• Servlet API life cycle methods
– init(): called when servlet is instantiated;
must return before any other methods will be
called
– service(): method called directly by server
when an HTTP request is received; default
service() method calls doGet() (or
related methods covered later)
– destroy(): called when server shuts down
Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Servlet Life Cycle
Example life cycle method:
attempt to initialize visits variable
from file

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Servlet Life Cycle

Exception to be thrown
if initialization fails and servlet
should not be instantiated

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Parameter Data
• The request object (which implements
HttpServletRequest) provides
information from the HTTP request to the
servlet
• One type of information is parameter data,
which is information from the query string
portion of the HTTP request
Query string with
one parameter
Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Parameter Data
• Parameter data is the Web analog of
arguments in a method call:

• Query string syntax and semantics

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Parameter Data
• Query string syntax and semantics
– Multiple parameters separated by &
– Order of parameters does not matter
– All parameter values are strings
Value of arg is empty string

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Parameter Data
• A parameter name or value can be any
sequence of 8-bit characters
• URL encoding is used to represent nonalphanumeric characters:
Value of arg is
‘a String’

• URL decoding applied by server to
retrieve intended name or value
Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Parameter Data
• URL encoding algorithm

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Parameter Data

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Parameter Data

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Parameter Data

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Parameter Data
Must escape XML special characters in
all user-supplied data before adding to HTML
to avoid cross-site scripting attacks

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Parameter Data
• Cross-site scripting
Attacker

Comment containing
<script> element
Blogging Web
site

Victim

Document containing
attacker’s comment (and script)

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Parameter Data

Also need to escape quotes within
attribute values.

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Parameter Data

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Parameter Data
• A form automatically generates a query
string when submitted
– Parameter name specified by value of name
attributes of form controls
– Parameter value depends on control type
Value for checkbox
specified by value attribute

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Parameter Data

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Parameter Data
username

lifestory
doit

boxgroup1 (values same as labels)

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Parameter Data
• Query string produced by browser (all one
line):

Checkbox parameters have same name values;
only checked boxes have corresponding parameters

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Parameter Data
• GET vs. POST for the method attribute of
forms:
– GET:
• Query string is part of URL
• Length of query string may be limited
• Recommended when parameter data is not stored
or updated on the server, but used only to request
information (e.g., search engine query)
– The URL can be bookmarked or emailed and the same
data will be passed to the server when the URL is
revisited

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Parameter Data

Browser content copyright 2004 Google, Inc. Used by permission.

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Parameter Data
• GET vs. POST method for forms:
– POST:
• Query string is sent as body of HTTP request
• Length of query string is unlimited
• Recommended if parameter data is intended to
cause the server to update stored data
• Most browsers will warn you if they are about to
resubmit POST data to avoid duplicate updates

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Parameter Data

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions
• Many interactive Web sites spread user
data entry out over several pages:
– Ex: add items to cart, enter shipping
information, enter billing information

• Problem: how does the server know which
users generated which HTTP requests?
– Cannot rely on standard HTTP headers to
identify a user

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions

Server sends back
new unique
session ID when
the request has
none

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions

Client that supports
session stores the
ID and sends it
back to the server
in subsequent
requests

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions

Server knows
that all of these
requests are
from the same
client. The
set of requests
is known as a
session.

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions
And the server
knows that all
of these
requests are
from a different
client.

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions

HttpSession object is created by server when a
servlet calls getSession() method on its
HttpServletRequest parameter.
getSession() method returns HttpSession object
associated with this HTTP request.
• Creates new HttpSession object if no
valid session ID in HTTP request
• Otherwise, returns previously created
HttpSession object containing the session ID

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions

Boolean indicating whether returned
object was newly created or already
existed.

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions

Incremented once per session

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions

Three web
pages produced
by a single servlet

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions
,,,

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions
,,,

Session attribute is a
name/value pair

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions
,,,

Session attribute will
have null value until
a value is assigned

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions
,,,

Generate
sign-in form
if session is
new or
signIn
attribute has no value,
generate weclome-back page
otherwise.

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions

Sign-in form

Welcome-back
page

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions
Second argument
(“Greeting”) used as
action attribute value
(relative URL)

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions

Form will be sent using POST HTTP
Method, so doPost() method will be called

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions

Text field containing
user name is named
signIn

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions
…

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions
…
Retrieve
signIn
parameter value

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions
…

Normal
processing:
signIn
parameter
is present in
HTTP request

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions
…

Generate
HTML for
response

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions

Thank-you page

Must escape
XML special
characters in
user input

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions
…

Assign a
value to the
signIn session
attribute

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions
• Session attribute methods:
– setAttribute(String name, Object
value): creates a session attribute with the
given name and value
– Object getAttribute(String name):
returns the value of the session attribute
named name, or returns null if this session
does not have an attribute with this name

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions
…

Error
processing
(return user
to sign-in form)

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Sessions
• By default, each session expires if a
server-determined length of time elapses
between a session’s HTTP requests
– Server destroys the corresponding session
object

• Servlet code can:
– Terminate a session by calling
invalidate() method on session object
– Set the expiration time-out duration (secs) by
calling setMaxInactiveInterval(int)
Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Cookies
• A cookie is a name/value pair in the SetCookie header field of an HTTP response
• Most (not all) clients will:
– Store each cookie received in its file system
– Send each cookie back to the server that sent
it as part of the Cookie header field of
subsequent HTTP requests

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Cookies

Tomcat sends
session ID as value
of cookie named
JSESSIONID

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Cookies

Cookie-enabled
browser returns
session ID as value
of cookie named
JSESSIONID

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Cookies
• Servlets can set cookies explicitly
– Cookie class used to represent cookies
– request.getCookies() returns an array of
Cookie instances representing cookie data in
HTTP request
– response.addCookie(Cookie) adds a
cookie to the HTTP response

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Cookies

Cookies are expired by
client (server can request
expiration date)

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Cookies

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Cookies

Return array of cookies
contained in HTTP request

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Cookies

Search for
cookie
named
COUNT and
extract value
as an int

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Cookies

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Cookies
Send
replacement
cookie value
to client
(overwrites
existing cookie)

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Cookies

Should call
addCookie()
before writing
HTML

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Cookies
Privacy issues
HTTP request to
intended site

Client

HTTP response:
HTML document
including ad <img>

Web site
providing
requested
content

HTTP request for
ad image
Image
plus Set-Cookie
in response:
third-party cookie

Web site
providing
banner
ads

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Cookies
Privacy issues
HTTP request to 2nd
intended site

Client

HTTP response:
HTML document
including ad <img>

Web site
providing
requested
content

Second
Web site
providing
requested
content

HTTP request for
ad image plus Cookie (identifies user)
Image

Web site
providing
banner
ads

Based on
Referer, I know two
Web sites that
this user has
visited

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Cookies
Privacy issues
• Due to privacy concerns, many users
block cookies
– Blocking may be fine-tuned. Ex: Mozilla
allows
• Blocking of third-party cookies
• Blocking based on on-line privacy policy

• Alternative to cookies for maintaining
session: URL rewriting

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
URL Rewriting

Tomcat adds
session ID within
HTML document
to all URL’s
referring to the
servlet

Session ID = 4235

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
URL Rewriting

Subsequent
request will contain
session ID in the
URL of the request

Session ID = 4235

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
URL Rewriting

Next response must
again add session ID
to all URL’s

Session ID = 4235

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
URL Rewriting
• Original (relative) URL:
href=“URLEncodedGreeting”

• URL containing session ID:
href=“URLEncodedGreeting;jsessionid=0157B9E85”
Path parameter

• Path parameter is treated differently than
query string parameter
– Ex: invisible to getParameter()
Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
URL Rewriting
• HttpServletResponse method
encodeURL() will add session id path
parameter to argument URL
Original
servlet
Relative URL of servlet
Servlet
using URL
rewriting

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
URL Rewriting
• Must rewrite every servlet URL in every
document
• Security issues
URL with
session ID
7152

Web site using
URL rewriting

User A

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
URL Rewriting
• Must rewrite every servlet URL in every
document
• Security issues
URL with
session ID
7152

User A

Web site using
URL rewriting

Email URL

User B

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
URL Rewriting
• Must rewrite every servlet URL in every
document
• Security issues
URL with
session ID
7152

User A

Web site using
URL rewriting

Email URL

Visit Web site with
session ID 7152

User B

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
More Servlet Methods

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
More Servlet Methods

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
More Servlet Methods

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
More Servlet Methods
• Response buffer
– All data sent to the PrintWriter object is
stored in a buffer
– When the buffer is full, it is automatically
flushed:
• Contents are sent to the client (preceded by
header fields, if this is the first flush)
• Buffer becomes empty

– Note that all header fields must be defined
before the first buffer flush
Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
More Servlet Methods

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
More Servlet Methods
• In addition to doGet() and doPost(),
servlets have methods corresponding to
other HTTP request methods
– doHead(): automatically defined if doGet()
is overridden
– doOptions(), doTrace(): useful default
methods provided
– doDelete(), doPut(): override to support
these methods
Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Data Storage
• Almost all web applications (servlets or related
dynamic web server software) store and retrieve
data
– Typical web app uses a data base management
system (DBMS)
– Another option is to use the file system
– Not web technologies, so beyond our scope

• Some Java data storage details provided in
Appendices B (file system) and C (DBMS)
• One common problem: concurrency
Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Concurrency

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Concurrency
• Tomcat creates a separate thread for
each HTTP request
• Java thread state saved:
– Which statement to be executed next
– The call stack: where the current method will
return to, where that method will return to, etc.
plus parameter values for each method
– The values of local variables for all methods
on the call stack
Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Concurrency
• Some examples of values that are not
saved when a thread is suspended:
– Values of instance variables (variables
declared outside of methods)
– Values of class variables (variables declared
as static outside of methods)
– Contents of files and other external resources

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Concurrency

// Output HTML document

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Concurrency

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Concurrency
• Java support thread synchronization
Only one thread at
at time can call doGet()

– Only one synchronized method within a class
can be called at any one time

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Concurrency

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Concurrency
• Web application with multiple servlet
classes and shared resource:

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Concurrency
• Solution: create a shared class with
synchronized static methods called by
both servlets

CounterReader

readAndReset()

CounterFile

incr()

CounterWriter

File
Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Common Gateway Interface
• CGI was the earliest standard technology
used for dynamic server-side content
• CGI basics:
– HTTP request information is stored in
environment variables (e.g.,
QUERY_STRING, REQUEST_METHOD,
HTTP_USER_AGENT)
– Program is executed, output is returned in
HTTP response
Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
Common Gateway Interface
• Advantage:
– Program can be written in any programming
language (Perl frequently used)

• Disadvantages:
– No standard for concepts such as session
– May be slower (programs normally run in
separate processes, not server process)

Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s

Contenu connexe

En vedette

The Glass Class - Tutorial 2 - Mirror API
The Glass Class - Tutorial 2 - Mirror APIThe Glass Class - Tutorial 2 - Mirror API
The Glass Class - Tutorial 2 - Mirror APIGun Lee
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript ObjectsReem Alattas
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods pptkamal kotecha
 
Java Servlets
Java ServletsJava Servlets
Java ServletsNitin Pai
 

En vedette (7)

JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 
The Glass Class - Tutorial 2 - Mirror API
The Glass Class - Tutorial 2 - Mirror APIThe Glass Class - Tutorial 2 - Mirror API
The Glass Class - Tutorial 2 - Mirror API
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 
Java servlets
Java servletsJava servlets
Java servlets
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 

Similaire à Java servlet

Qtp manual testing tutorials by QuontraSolutions
Qtp manual testing tutorials by QuontraSolutionsQtp manual testing tutorials by QuontraSolutions
Qtp manual testing tutorials by QuontraSolutionsQUONTRASOLUTIONS
 
Web-01-HTTP.pptx
Web-01-HTTP.pptxWeb-01-HTTP.pptx
Web-01-HTTP.pptxAliZaib71
 
2014 CrossRef Workshops: System Update
2014 CrossRef Workshops: System Update2014 CrossRef Workshops: System Update
2014 CrossRef Workshops: System UpdateCrossref
 
SCWCD : The servlet model : CHAP : 2
SCWCD  : The servlet model : CHAP : 2SCWCD  : The servlet model : CHAP : 2
SCWCD : The servlet model : CHAP : 2Ben Abdallah Helmi
 
SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2Ben Abdallah Helmi
 
application of http.pptx
application of http.pptxapplication of http.pptx
application of http.pptxssuseraf60311
 
Advance java session 17
Advance java session 17Advance java session 17
Advance java session 17Smita B Kumar
 
Database Firewall from Scratch
Database Firewall from ScratchDatabase Firewall from Scratch
Database Firewall from ScratchDenis Kolegov
 
Environment Canada's Data Management Service
Environment Canada's Data Management ServiceEnvironment Canada's Data Management Service
Environment Canada's Data Management ServiceSafe Software
 
Как разработать DBFW с нуля
Как разработать DBFW с нуляКак разработать DBFW с нуля
Как разработать DBFW с нуляPositive Hack Days
 
Thoth - Real-time Solr Monitor and Search Analysis Engine: Presented by Damia...
Thoth - Real-time Solr Monitor and Search Analysis Engine: Presented by Damia...Thoth - Real-time Solr Monitor and Search Analysis Engine: Presented by Damia...
Thoth - Real-time Solr Monitor and Search Analysis Engine: Presented by Damia...Lucidworks
 
Secrets of highly_avail_oltp_archs
Secrets of highly_avail_oltp_archsSecrets of highly_avail_oltp_archs
Secrets of highly_avail_oltp_archsTarik Essawi
 
2016 bioinformatics i_io_wim_vancriekinge
2016 bioinformatics i_io_wim_vancriekinge2016 bioinformatics i_io_wim_vancriekinge
2016 bioinformatics i_io_wim_vancriekingeProf. Wim Van Criekinge
 
How a search engine works slide
How a search engine works slideHow a search engine works slide
How a search engine works slideSovan Misra
 
(ATS6-PLAT02) Accelrys Catalog and Protocol Validation
(ATS6-PLAT02) Accelrys Catalog and Protocol Validation(ATS6-PLAT02) Accelrys Catalog and Protocol Validation
(ATS6-PLAT02) Accelrys Catalog and Protocol ValidationBIOVIA
 
Oracle Forms : Query Triggers
Oracle Forms : Query TriggersOracle Forms : Query Triggers
Oracle Forms : Query TriggersSekhar Byna
 

Similaire à Java servlet (20)

Qtp manual testing tutorials by QuontraSolutions
Qtp manual testing tutorials by QuontraSolutionsQtp manual testing tutorials by QuontraSolutions
Qtp manual testing tutorials by QuontraSolutions
 
Filter
FilterFilter
Filter
 
Filter
FilterFilter
Filter
 
Web-01-HTTP.pptx
Web-01-HTTP.pptxWeb-01-HTTP.pptx
Web-01-HTTP.pptx
 
2014 CrossRef Workshops: System Update
2014 CrossRef Workshops: System Update2014 CrossRef Workshops: System Update
2014 CrossRef Workshops: System Update
 
SCWCD : The servlet model : CHAP : 2
SCWCD  : The servlet model : CHAP : 2SCWCD  : The servlet model : CHAP : 2
SCWCD : The servlet model : CHAP : 2
 
SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2
 
application of http.pptx
application of http.pptxapplication of http.pptx
application of http.pptx
 
Advance java session 17
Advance java session 17Advance java session 17
Advance java session 17
 
AD102 - Break out of the Box
AD102 - Break out of the BoxAD102 - Break out of the Box
AD102 - Break out of the Box
 
Database Firewall from Scratch
Database Firewall from ScratchDatabase Firewall from Scratch
Database Firewall from Scratch
 
Environment Canada's Data Management Service
Environment Canada's Data Management ServiceEnvironment Canada's Data Management Service
Environment Canada's Data Management Service
 
Как разработать DBFW с нуля
Как разработать DBFW с нуляКак разработать DBFW с нуля
Как разработать DBFW с нуля
 
Thoth - Real-time Solr Monitor and Search Analysis Engine: Presented by Damia...
Thoth - Real-time Solr Monitor and Search Analysis Engine: Presented by Damia...Thoth - Real-time Solr Monitor and Search Analysis Engine: Presented by Damia...
Thoth - Real-time Solr Monitor and Search Analysis Engine: Presented by Damia...
 
Secrets of highly_avail_oltp_archs
Secrets of highly_avail_oltp_archsSecrets of highly_avail_oltp_archs
Secrets of highly_avail_oltp_archs
 
2016 bioinformatics i_io_wim_vancriekinge
2016 bioinformatics i_io_wim_vancriekinge2016 bioinformatics i_io_wim_vancriekinge
2016 bioinformatics i_io_wim_vancriekinge
 
How a search engine works slide
How a search engine works slideHow a search engine works slide
How a search engine works slide
 
Oracle Tracing
Oracle TracingOracle Tracing
Oracle Tracing
 
(ATS6-PLAT02) Accelrys Catalog and Protocol Validation
(ATS6-PLAT02) Accelrys Catalog and Protocol Validation(ATS6-PLAT02) Accelrys Catalog and Protocol Validation
(ATS6-PLAT02) Accelrys Catalog and Protocol Validation
 
Oracle Forms : Query Triggers
Oracle Forms : Query TriggersOracle Forms : Query Triggers
Oracle Forms : Query Triggers
 

Plus de philipsinter

Plus de philipsinter (10)

Fundamentals of Database system
Fundamentals of Database systemFundamentals of Database system
Fundamentals of Database system
 
MULTIMEDIA Cocomo forum version5
MULTIMEDIA Cocomo forum version5 MULTIMEDIA Cocomo forum version5
MULTIMEDIA Cocomo forum version5
 
Multimedia
Multimedia Multimedia
Multimedia
 
multimedia 01
multimedia 01multimedia 01
multimedia 01
 
Xml 215-presentation
Xml 215-presentationXml 215-presentation
Xml 215-presentation
 
Xml
XmlXml
Xml
 
Server side
Server sideServer side
Server side
 
Dbms
DbmsDbms
Dbms
 
Lecture2
Lecture2Lecture2
Lecture2
 
Final vlsi projectreport
Final vlsi projectreportFinal vlsi projectreport
Final vlsi projectreport
 

Java servlet

  • 1. CSI3140 WWW Structures, Techniques, and Standards Chapter 6 Server-side Programming: Java Servlets Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 2. Server-side Programming • The combination of – HTML – JavaScript – DOM is sometimes referred to as Dynamic HTML (DHTML) • Web pages that include scripting are often called dynamic pages (vs. static) Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 3. Server-side Programming • Similarly, web server response can be static or dynamic – Static: HTML document is retrieved from the file system and returned to the client – Dynamic: HTML document is generated by a program in response to an HTTP request • Java servlets are one technology for producing dynamic server responses – Servlet is a Java class instantiated by the server to produce a dynamic response Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 4. Servlet Overview Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 5. Servlet Overview 1. When server starts, it instantiates servlets 2. Server receives HTTP request, determines need for dynamic response 3. Server selects the appropriate servlet to generate the response, creates request/response objects, and passes them to a method on the servlet instance 4. Servlet adds information to response object via method calls 5. Server generates HTTP response based on information stored in response object Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 6. Hello World! Servlet Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 7. Hello World! Servlet All servlets we will write are subclasses of HttpServlet Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 8. Hello World! Servlet Server calls doGet() in response to GET request Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 9. Hello World! Servlet Interfaces implemented by request/response objects Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 10. Hello World! Servlet Production servlet should catch these exceptions Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 11. Hello World! Servlet • JWSDP Tomcat server exception handling: – Writing a trace for the exception in logs/jwsdp_log.*.txt log file – Returning HTML page to client that may (or may not) contain partial exception trace • If servlet prints a stack trace itself by calling printStackTrace(), or if it writes debugging output to System.out or System.err, this output will be appended to the file logs/launcher.server.log Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 12. Hello World! Servlet First two things done by typical servlet; must be in this order Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 13. Hello World! Servlet Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 14. Hello World! Servlet HTML generated by calling print() or println() on the servlet’s PrintWriter object Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 15. Hello World! Servlet Good practice to explicitly close the PrintWriter when done Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 16. Servlets vs. Java Applications • Servlets do not have a main() – The main() is in the server – Entry point to servlet code is via call to a method (doGet() in the example) • Servlet interaction with end user is indirect via request/response object APIs – Actual HTTP request/response processing is handled by the server • Primary servlet output is typically HTML Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 17. Running Servlets • Simple way to run a servlet (better later): 1. Compile servlet (make sure that JWSDP libraries are on path) 2. Copy .class file to shared/classes directory 3. (Re)start the Tomcat web server 4. If the class is named ServletHello, browse to http://localhost:8080/servlet/ServletHello Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 18. Dynamic Content Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 19. Dynamic Content Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 20. Dynamic Content Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 21. Dynamic Content • Potential problems: – Assuming one instance of servlet on one server, but • Many Web sites are distributed over multiple servers • Even a single server can (not default) create multiple instances of a single servlet – Even if the assumption is correct, this servlet does not handle concurrent accesses properly • We’ll deal with this later in the chapter Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 22. Servlet Life Cycle • Servlet API life cycle methods – init(): called when servlet is instantiated; must return before any other methods will be called – service(): method called directly by server when an HTTP request is received; default service() method calls doGet() (or related methods covered later) – destroy(): called when server shuts down Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 23. Servlet Life Cycle Example life cycle method: attempt to initialize visits variable from file Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 24. Servlet Life Cycle Exception to be thrown if initialization fails and servlet should not be instantiated Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 25. Parameter Data • The request object (which implements HttpServletRequest) provides information from the HTTP request to the servlet • One type of information is parameter data, which is information from the query string portion of the HTTP request Query string with one parameter Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 26. Parameter Data • Parameter data is the Web analog of arguments in a method call: • Query string syntax and semantics Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 27. Parameter Data • Query string syntax and semantics – Multiple parameters separated by & – Order of parameters does not matter – All parameter values are strings Value of arg is empty string Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 28. Parameter Data • A parameter name or value can be any sequence of 8-bit characters • URL encoding is used to represent nonalphanumeric characters: Value of arg is ‘a String’ • URL decoding applied by server to retrieve intended name or value Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 29. Parameter Data • URL encoding algorithm Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 30. Parameter Data Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 31. Parameter Data Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 32. Parameter Data Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 33. Parameter Data Must escape XML special characters in all user-supplied data before adding to HTML to avoid cross-site scripting attacks Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 34. Parameter Data • Cross-site scripting Attacker Comment containing <script> element Blogging Web site Victim Document containing attacker’s comment (and script) Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 35. Parameter Data Also need to escape quotes within attribute values. Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 36. Parameter Data Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 37. Parameter Data • A form automatically generates a query string when submitted – Parameter name specified by value of name attributes of form controls – Parameter value depends on control type Value for checkbox specified by value attribute Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 38. Parameter Data Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 39. Parameter Data username lifestory doit boxgroup1 (values same as labels) Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 40. Parameter Data • Query string produced by browser (all one line): Checkbox parameters have same name values; only checked boxes have corresponding parameters Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 41. Parameter Data • GET vs. POST for the method attribute of forms: – GET: • Query string is part of URL • Length of query string may be limited • Recommended when parameter data is not stored or updated on the server, but used only to request information (e.g., search engine query) – The URL can be bookmarked or emailed and the same data will be passed to the server when the URL is revisited Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 42. Parameter Data Browser content copyright 2004 Google, Inc. Used by permission. Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 43. Parameter Data • GET vs. POST method for forms: – POST: • Query string is sent as body of HTTP request • Length of query string is unlimited • Recommended if parameter data is intended to cause the server to update stored data • Most browsers will warn you if they are about to resubmit POST data to avoid duplicate updates Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 44. Parameter Data Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 45. Sessions • Many interactive Web sites spread user data entry out over several pages: – Ex: add items to cart, enter shipping information, enter billing information • Problem: how does the server know which users generated which HTTP requests? – Cannot rely on standard HTTP headers to identify a user Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 46. Sessions Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 47. Sessions Server sends back new unique session ID when the request has none Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 48. Sessions Client that supports session stores the ID and sends it back to the server in subsequent requests Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 49. Sessions Server knows that all of these requests are from the same client. The set of requests is known as a session. Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 50. Sessions And the server knows that all of these requests are from a different client. Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 51. Sessions HttpSession object is created by server when a servlet calls getSession() method on its HttpServletRequest parameter. getSession() method returns HttpSession object associated with this HTTP request. • Creates new HttpSession object if no valid session ID in HTTP request • Otherwise, returns previously created HttpSession object containing the session ID Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 52. Sessions Boolean indicating whether returned object was newly created or already existed. Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 53. Sessions Incremented once per session Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 54. Sessions Three web pages produced by a single servlet Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 55. Sessions Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 56. Sessions Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 57. Sessions Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 58. Sessions Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 59. Sessions ,,, Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 60. Sessions ,,, Session attribute is a name/value pair Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 61. Sessions ,,, Session attribute will have null value until a value is assigned Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 62. Sessions ,,, Generate sign-in form if session is new or signIn attribute has no value, generate weclome-back page otherwise. Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 63. Sessions Sign-in form Welcome-back page Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 64. Sessions Second argument (“Greeting”) used as action attribute value (relative URL) Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 65. Sessions Form will be sent using POST HTTP Method, so doPost() method will be called Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 66. Sessions Text field containing user name is named signIn Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 67. Sessions … Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 68. Sessions … Retrieve signIn parameter value Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 69. Sessions … Normal processing: signIn parameter is present in HTTP request Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 70. Sessions … Generate HTML for response Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 71. Sessions Thank-you page Must escape XML special characters in user input Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 72. Sessions … Assign a value to the signIn session attribute Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 73. Sessions • Session attribute methods: – setAttribute(String name, Object value): creates a session attribute with the given name and value – Object getAttribute(String name): returns the value of the session attribute named name, or returns null if this session does not have an attribute with this name Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 74. Sessions … Error processing (return user to sign-in form) Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 75. Sessions • By default, each session expires if a server-determined length of time elapses between a session’s HTTP requests – Server destroys the corresponding session object • Servlet code can: – Terminate a session by calling invalidate() method on session object – Set the expiration time-out duration (secs) by calling setMaxInactiveInterval(int) Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 76. Cookies • A cookie is a name/value pair in the SetCookie header field of an HTTP response • Most (not all) clients will: – Store each cookie received in its file system – Send each cookie back to the server that sent it as part of the Cookie header field of subsequent HTTP requests Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 77. Cookies Tomcat sends session ID as value of cookie named JSESSIONID Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 78. Cookies Cookie-enabled browser returns session ID as value of cookie named JSESSIONID Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 79. Cookies • Servlets can set cookies explicitly – Cookie class used to represent cookies – request.getCookies() returns an array of Cookie instances representing cookie data in HTTP request – response.addCookie(Cookie) adds a cookie to the HTTP response Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 80. Cookies Cookies are expired by client (server can request expiration date) Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 81. Cookies Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 82. Cookies Return array of cookies contained in HTTP request Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 83. Cookies Search for cookie named COUNT and extract value as an int Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 84. Cookies Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 85. Cookies Send replacement cookie value to client (overwrites existing cookie) Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 86. Cookies Should call addCookie() before writing HTML Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 87. Cookies Privacy issues HTTP request to intended site Client HTTP response: HTML document including ad <img> Web site providing requested content HTTP request for ad image Image plus Set-Cookie in response: third-party cookie Web site providing banner ads Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 88. Cookies Privacy issues HTTP request to 2nd intended site Client HTTP response: HTML document including ad <img> Web site providing requested content Second Web site providing requested content HTTP request for ad image plus Cookie (identifies user) Image Web site providing banner ads Based on Referer, I know two Web sites that this user has visited Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 89. Cookies Privacy issues • Due to privacy concerns, many users block cookies – Blocking may be fine-tuned. Ex: Mozilla allows • Blocking of third-party cookies • Blocking based on on-line privacy policy • Alternative to cookies for maintaining session: URL rewriting Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 90. URL Rewriting Tomcat adds session ID within HTML document to all URL’s referring to the servlet Session ID = 4235 Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 91. URL Rewriting Subsequent request will contain session ID in the URL of the request Session ID = 4235 Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 92. URL Rewriting Next response must again add session ID to all URL’s Session ID = 4235 Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 93. URL Rewriting • Original (relative) URL: href=“URLEncodedGreeting” • URL containing session ID: href=“URLEncodedGreeting;jsessionid=0157B9E85” Path parameter • Path parameter is treated differently than query string parameter – Ex: invisible to getParameter() Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 94. URL Rewriting • HttpServletResponse method encodeURL() will add session id path parameter to argument URL Original servlet Relative URL of servlet Servlet using URL rewriting Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 95. URL Rewriting • Must rewrite every servlet URL in every document • Security issues URL with session ID 7152 Web site using URL rewriting User A Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 96. URL Rewriting • Must rewrite every servlet URL in every document • Security issues URL with session ID 7152 User A Web site using URL rewriting Email URL User B Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 97. URL Rewriting • Must rewrite every servlet URL in every document • Security issues URL with session ID 7152 User A Web site using URL rewriting Email URL Visit Web site with session ID 7152 User B Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 98. More Servlet Methods Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 99. More Servlet Methods Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 100. More Servlet Methods Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 101. More Servlet Methods • Response buffer – All data sent to the PrintWriter object is stored in a buffer – When the buffer is full, it is automatically flushed: • Contents are sent to the client (preceded by header fields, if this is the first flush) • Buffer becomes empty – Note that all header fields must be defined before the first buffer flush Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 102. More Servlet Methods Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 103. More Servlet Methods • In addition to doGet() and doPost(), servlets have methods corresponding to other HTTP request methods – doHead(): automatically defined if doGet() is overridden – doOptions(), doTrace(): useful default methods provided – doDelete(), doPut(): override to support these methods Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 104. Data Storage • Almost all web applications (servlets or related dynamic web server software) store and retrieve data – Typical web app uses a data base management system (DBMS) – Another option is to use the file system – Not web technologies, so beyond our scope • Some Java data storage details provided in Appendices B (file system) and C (DBMS) • One common problem: concurrency Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 105. Concurrency Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 106. Concurrency • Tomcat creates a separate thread for each HTTP request • Java thread state saved: – Which statement to be executed next – The call stack: where the current method will return to, where that method will return to, etc. plus parameter values for each method – The values of local variables for all methods on the call stack Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 107. Concurrency • Some examples of values that are not saved when a thread is suspended: – Values of instance variables (variables declared outside of methods) – Values of class variables (variables declared as static outside of methods) – Contents of files and other external resources Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 108. Concurrency // Output HTML document Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 109. Concurrency Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 110. Concurrency • Java support thread synchronization Only one thread at at time can call doGet() – Only one synchronized method within a class can be called at any one time Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 111. Concurrency Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 112. Concurrency • Web application with multiple servlet classes and shared resource: Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 113. Concurrency • Solution: create a shared class with synchronized static methods called by both servlets CounterReader readAndReset() CounterFile incr() CounterWriter File Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 114. Common Gateway Interface • CGI was the earliest standard technology used for dynamic server-side content • CGI basics: – HTTP request information is stored in environment variables (e.g., QUERY_STRING, REQUEST_METHOD, HTTP_USER_AGENT) – Program is executed, output is returned in HTTP response Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s
  • 115. Common Gateway Interface • Advantage: – Program can be written in any programming language (Perl frequently used) • Disadvantages: – No standard for concepts such as session – May be slower (programs normally run in separate processes, not server process) Dr. Thomas Tran – CSI3140 Lecture Notes (based on Dr. Jeffrey Jackson’s