Cookies and Sessions in Servlets

Servlets (part 2)
Dr Solange Karsenty
Hadassah Academic College
תוכן עניינים
א
י
ך
 
נ
י
ת
ן
 
ל
ע
ק
ו
ב
 
א
ח
ר
י
 
מ
צ
ב
 
ה
ג
ל
י
ש
ה
?
(
1
)
 
C
o
o
k
i
e
s
 
-
 
ח
ז
ר
ה
(
2
)
 
S
e
s
s
i
o
n
 
-
 
ח
ז
ר
ה
(
3
)
 
א
י
פ
ה
 
א
פ
ש
ר
 
ל
א
ח
ס
ן
 
פ
ר
מ
ט
ר
י
ם
?
ג
ל
ו
ב
א
ל
י
 
 
ל
כ
ל
 
ה
-
s
e
r
v
l
e
t
s
פ
ר
ט
י
 
ל
כ
ל
 
s
e
r
v
l
e
t
(
4
)
 
 
א
י
ך
 
ב
ו
נ
י
ם
 
א
ת
ר
 
מ
ו
ד
ו
ל
א
ר
י
?
C
h
a
i
n
i
n
g
 
S
e
r
v
l
e
t
s
R
e
q
u
e
s
t
D
i
s
p
a
t
c
h
e
r
 
(
i
n
c
l
u
d
e
/
f
o
r
w
a
r
d
,
 
d
i
f
f
e
r
e
n
c
e
 
r
e
d
i
r
e
c
t
)
3
(
1
)
 
C
o
o
k
i
e
s
 
-
 
ח
ז
ר
ה
C
o
o
k
i
e
s
:
 
מ
נ
ג
נ
ו
ן
 
ל
ש
מ
י
ר
ת
 
נ
ת
ו
נ
י
ם
 
ב
צ
ד
 
ה
ל
ק
ו
ח
מ
צ
ו
ר
ף
 
ל
כ
ו
ל
 
ב
ב
ק
ש
ה
 
ו
ת
ש
ו
ב
ה
 
h
t
t
p
כ
א
ש
ר
 
ש
ר
ת
 
ר
ו
צ
ה
 
ל
ר
ש
ו
ם
 
ק
ו
ק
י
,
 
ה
ו
א
 
ש
ו
ל
ח
 
א
ת
 
ה
ק
ו
ק
י
 
י
ח
ד
 
ע
ם
ה
ת
ש
ו
ב
ה
h
tt
p
 
 
ו
ה
ד
פ
ד
פ
ן
 
א
ח
ר
א
י
 
ע
ל
 
כ
ת
י
ב
ת
 
ה
ק
ו
ק
י
 
ב
מ
ח
ש
ב
 
ה
ל
ק
ו
ח
ג
ם
 
ק
ו
ד
 
ב
צ
ד
 
ל
ק
ו
ח
 
ק
ו
ר
א
/
כ
ו
ת
ב
 
ק
ו
ק
י
מ
צ
ג
ת
 
ס
מ
ס
ט
ר
 
א
׳
:
Cookies are 
private
 to each website: cookies of website x.y.com are not readable by z.com and vice versa.
Within a website, cookies can be 
associated to a folder
. It will be available to all pages in that folder and subdirectories (you can
hide cookies from parent folders).
Cookies are used for 
non-sensitive information 
(do not store credit cards) because the cookies file is readable on your computer
 You can 
manually delete
 cookies in your browser (in settings)
Cookies 
length is limited
; it cannot be used to store long information (around 4Kb, you can 
check on your browser
 the limit)
Cookies can have an 
expiration date
: these will be automatically erased at the expiration date (for example you may want to forget
stored user information after a month).
Cookies can be created, read and updated on the client side (with Javascript) 
AND on the server side
 (PHP, Java, javascript etc). So
how does code on the server side read/write cookies that are stored on the client? Because:
All cookies are sent to the server and back to the browser for each new http request (whenever you access a URL, click
on a link, submit a form, or when you perform an Ajax call). All cookies are sent to the server and attached back to the
page returned to the browser and the browser updates cookies (this is how the server can write cookies).
Managing Cookies
Get the cookies from the service request:
Cookie[]
 
HttpServletRequest.getCookies()
Add a cookie to the service response:
HttpServletResponse.addCookie(Cookie cookie)
Cookie getter methods:
getName()
, 
getValue()
, 
getPath()
, 
getDomain()
, 
getMaxAge
,
 getSecure
Cookie setter methods:
setValue()
 ,
 setPath()
, 
setDomain()
4
5
<html> <head>
  <title>Login Page</title>
  </head>
  <body>
    <h1>
Logon to My Site
</h1>
    <form action=
"/WelcomeBack" 
method
="get"
>
      Your Name:
      <input type=
"text" 
name=
"username"
>
      <input type=
"submit"
>
    </form>
  </body>
</html>
Example
File login.html
6
public class WelcomeBack extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException   {
 
String user = req.getParameter(
"username"
);
 
if (user == null) { 
// see (3)
 
    Cookie[] cookies = req.
getCookies()
;
 
    for (int i = 0 ; cookies!=null && i < cookies.length ; i++)
  
  if (cookies[i].getName().equals("
username
"))
  
    user = cookies[i].
getValue()
;
 
} else 
// user filled the name in the form
            res.
addCookie(new Cookie(
"username"
, user
))
; 
// see (2)
 
if (user != null)  
// see (2)
 
    res.setContentType(
"text/html"
);
 
    PrintWriter out = res.getWriter();
 
    out.println("
<html><body><h1>Welcome Back "
 + user +
 " </h1></html></body>"
);
 
} else {
         
// here we are in in the case user never filled the form so we send him
         // to the login page
         res.sendRedirect(
"/dbi-servlets/login.html"
);
       }
}
}
7
(1) This page is a static HTML page with
a form to call the WelcomeBack Servlet
8
(2) This page is the response of the
WelcomeBack
Servlet after the user has pressed the
submit button.
This is a GET request: the parameters
from the form are appended in the
request URL. The Servlet method
doGet() is called.
9
(3) This page is the response of the
WelcomeBack Servlet when one enters the
URL http://
/WelcomeBack in the brower
and hits return:
This is a simple GET request sent to the
Servlet without any parameters. The Servlet
method doGet() is called.
In this example, the user previously entered
his name with the form so it is read by the
servlet and displayed.
10
(2) Sessions (
חזרה
)
כ
א
ש
ר
 
מ
ג
י
ע
ה
 
ב
ק
ש
ה
 
h
t
t
p
 
ר
א
ש
ו
נ
ה
 
ל
ש
ר
ת
 
,
 
ה
ו
א
 
מ
י
י
צ
ר
 
ו
מ
ח
ז
י
ר
 
ק
ו
ק
י
ש
מ
כ
י
ל
 
מ
פ
ת
ח
 
ה
s
e
s
s
i
o
n
-
 
(
s
e
s
s
i
o
n
 
I
D
)
מ
ע
כ
ש
י
ו
 
כ
ל
 
ב
ק
ש
ה
 
ש
י
ו
צ
א
ת
 
מ
ה
ד
פ
ד
פ
ן
 
ש
ו
ל
ח
ת
 
א
ת
 
ה
ק
ו
ק
י
ב
מ
ק
ב
י
ל
 
כ
ל
 
ב
ב
ק
ש
ה
 
ש
ח
ו
ז
ר
ת
 
מ
ה
ש
ר
ת
 
כ
ו
ל
ל
ת
 
א
ת
 
ה
ק
ו
ק
י
ה
ש
ר
ת
 
ב
ו
ד
ק
 
א
ת
 
ה
ק
ו
ק
י
 
ו
מ
ח
ז
י
ק
 
s
e
s
s
i
o
n
 
פ
ת
ו
ח
 
כ
ל
 
ע
ו
ד
 
י
ש
 
s
e
s
s
i
o
n
 
I
D
ב
ת
ו
ק
ף
e
x
p
i
r
a
t
i
o
n
 
t
i
m
e
:
 
נ
י
ת
ן
 
ל
ה
ג
ד
י
ר
 
א
ו
ר
ך
 
ז
מ
ן
 
ש
ל
 
s
e
s
s
i
o
n
 
 
ב
צ
ד
ה
ש
ר
ת
.
 
מ
כ
י
ו
ו
ן
 
ש
ז
ה
 
ת
ל
ו
י
 
ב
ל
ק
ו
ח
 
א
י
ן
 
א
ב
ט
ח
ה
 
ש
ז
ה
 
י
י
ש
א
ר
 
פ
ת
ו
ח
.
11
Accessing the Session Data
Session data is represented by the class 
HttpSession
Use the methods 
getSesssion()
 
or 
getSession(true)
 
of the
doGet/doPost/doXXX request to get the current HttpSession object, or
to create one if it doesn’t exist
Use 
getSession(false)
 
if you do not want to create a new session if no
session exists
12
HttpSession Methods
C
o
o
k
i
e
s
 
 
מ
א
ח
ס
ן
 
ר
ק
S
t
r
i
n
g
s
ב
נ
י
ג
ו
ד
 
ל
-
 
S
e
s
s
i
o
n
ש
י
כ
ו
ל
 
ל
א
ח
ס
ן
 
א
ו
ב
י
י
ק
ט
י
ם
 
(
A
t
t
r
i
b
u
t
e
s
)
Session data is accessed in a hash-table fashion:
-
setAttribute(String name,Object value)
-
איפה זה נשמר? 
-
Object getAttribute(String name)
More methods:
-
removeAttribute, getAttributeNames
-
Invalidate
-
isNew, getId
-
getCreationTime, getLastAccessedTime
-
getMaxInactiveInterval, setMaxInactiveInterval
(
מ
ח
י
ק
ה
)
13
דוגמא: סל קניות
In the following example a basic shopping cart for an online store is
implemented
The application consists of two Servlets:
-
Store.java
:
 the main store site
-
ShoppingCart.java
:
 handles cart manipulation
-
Each servlet handles different pages, depending on the shopping
cart content and if the user already visited the store or not
-
In general, 
a servlet handles multiple pages
 corresponding to
different states
 of website
14
(1)
This is displayed by the Store servlet
as the user enters the http://
/Store
URL in the browser and hits return. A
GET request is sent to the Servlet.
The user never visited before and no
shopping cart object exists yet in the
session.
15
(2) This is displayed by the ShoppingCart
servlet as the user hits the submit
button of previous page.
16
(3) This is displayed by the Store servlet
as the user enters the http://
/Store
URL in the browser and hits return. A
GET request is sent to the Servlet. The
user has a non empty shopping cart
displayed by the servlet.
17
18
public class Store extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  
res.setContentType(
"text/html"
);
  
PrintWriter out = res.getWriter();
  
out.println(
"<HTML><HEAD><LINK rel=
'
stylesheet
'
 type=
'
text/css
 href= 
'
cartstyle.css
'
></HEAD><BODY>"
);
  
HttpSession session = req.getSession();    
  
List itemList = (List)session.getAttribute(
"item-list"
);
  
if(itemList==null)
 
{
  
  
 
out.println(
"Hello new visitor!<br><br>"
);
  
 
itemList = new LinkedList();
  
 
session()
.setAttribute
(
"item-list"
, itemList);
 
  
}
  
out.println(
"Your Shopping Cart:<OL><I>"
);
    
 
for(Iterator it = itemList.iterator(); it.hasNext();)
        out.println(
"<LI>"
+it.next()+
"</LI>"
);
  
out.println(
"</I></OL>"
);
  
out.println(
"<FORM method='POST' action=‘ShoppingCart'>Add item:<INPUT name='item' type='text'>"
    
  
+ "
<INPUT type='submit' value='send'><BR><BR><INPUT type='submit' value='Empty Cart' name='clear'>"
     
 
+
 "</FORM></BODY></HTML>"
);
    
 
out.close();
  }
}
19
public class ShoppingCart extends HttpServlet {
  public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
 
res.setContentType(
"text/html"
);
 
PrintWriter out = res.getWriter();
 
out.println(
"<HTML><HEAD><LINK rel='stylesheet’ type='text/css' href='cartstyle.css'></HEAD><BODY>"
);
 
 
List items = (List)req.getSession().getAttribute("item-list");
   if (req.getParameter(
"clear"
)!= null) {
  
 
 
// user hit the  empty cart button (button name=“clear”)
      
 
 
items.clear();
       
 
out.println(
"Your Shopping Cart is Empty!"
); }
   else
 
{
   
// user hit submit and added an item to cart
      
 
String item = req.getParameter(
"item"
);
      
 
items.add(item); 
      
 
out.println(
"The item <I>" 
+ item + 
"</I> was added to your cart."
);  }
      
 
out.println(
"<BR><BR><A HREF='Store'> return to store</A>"
);
      
 
out.println(
"</BODY></HTML>"
);
     
 
// 
it’s important close = to signal the browser we are finished sending the output
 
  
 
out.close();
} }
20
(3) ServletContext
ת
ק
ש
ו
ר
ת
 
ע
ם
 
S
e
r
v
l
e
t
 
c
o
n
t
a
i
n
e
r
 
 
ד
ר
ך
 
S
e
r
v
l
e
t
C
o
n
t
e
x
t
 
o
b
j
e
c
t
Can store Web application 
initialization parameters
פ
ר
מ
ט
ר
י
ם
 
י
ת
ח
ו
ל
 
ש
ל
 
ה
א
ת
ר
 
 
 
(
i
n
 
S
e
r
v
l
e
t
C
o
n
t
e
x
t
.
g
e
t
I
n
i
t
P
a
r
a
m
e
t
e
r
s
)
Can store and manipulate 
application-shared attributes
פ
ר
מ
ט
ר
י
ם
 
ז
מ
י
נ
י
ם
 
ל
כ
ל
 
ה
-
s
e
r
v
l
e
t
s
 
 
(
i
n
 
S
e
r
v
l
e
t
C
o
n
t
e
x
t
.
g
e
t
/
s
e
t
A
t
t
r
i
b
u
t
e
)
Can be used to access the 
logger
ה
ד
פ
ס
ת
 
d
e
b
u
g
g
i
n
g
 
(
א
י
ן
 
s
t
d
o
u
t
 
ב
פ
י
ת
ו
ח
 
w
e
b
!
)
Can be used to 
dispatch requests 
to other resources
 
21
ServletContext Methods
Access 
initialization parameters
:
getInitParameter(String name),
getInitParameterNames()
// paramscan be defined with the @WebInitParam annotation
 
Web-application attributes
:
getAttribute(String name), getAttributeNames()
setAttribute(String, Object),
removeAttribute(String)
Transform context-relative paths to absolute paths:
ש
י
מ
ו
ש
י
 
כ
א
ש
ר
 
ר
ו
צ
י
ם
 
ל
ג
ש
ת
 
ל
ק
ו
ב
ץ
 
ש
י
ו
ש
ב
 
ב
א
ת
ר
getRealPath(String path),
URL getResource(String path)
ServletContext Methods
Write to the application 
log
:
log(String msg), log(String message, Throwable exception)
Get a resource dispatcher (discussed later):
 
RequestDispatcher getRequestDispatcher(String path)
 Name and version of the servlet container:
 
String getServerInfo()
22
23
ServletContext
תחרות ב-
There is a 
single ServletContext per Web application
Different Servlets will get 
the same ServletContext object
,
when calling 
getServletContext() 
during different sessions
You can lock the context to protect a critical section from all
Web-application accesses
נ
ו
ש
א
 
ל
ש
י
ע
ו
ר
 
ה
ב
א
ב
נ
י
ת
 
ה
-
r
e
s
p
o
n
s
e
S
e
r
v
l
e
t
 
י
כ
ו
ל
 
ל
ה
י
ע
ז
ר
 
ב
ר
כ
י
ב
י
ם
 
א
ח
ר
י
ם
 
ע
ל
 
מ
נ
ת
 
ל
ה
ח
ז
י
ר
 
r
e
s
p
o
n
s
e
o
t
h
e
r
 
s
e
r
v
l
e
t
s
H
t
m
l
 
p
a
g
e
s
2
 
ד
ר
כ
י
ם
ה
ע
ב
ר
ה
 
ש
ל
 
ה
-
r
e
q
u
e
s
t
 
ל
ט
י
פ
ו
ל
 
ר
כ
י
ב
 
א
ח
ר
ש
י
מ
ו
ש
 
ב
ר
כ
י
ב
 
א
ח
ר
 
ע
ל
 
מ
נ
ת
 
ל
ה
ר
כ
י
ב
 
א
ת
 
ה
-
r
e
s
p
o
n
s
e
25
(4) RequestDispatcher
א
ו
ב
י
י
ק
ט
 
ז
מ
י
ן
 
ב
כ
ל
 
s
e
r
v
l
e
t
 
ה
מ
א
פ
ש
ר
 
ז
א
ת
ה
״
ר
כ
י
ב
״
 
י
כ
ו
ל
 
ל
ה
י
ו
ת
 
ד
י
נ
א
מ
י
 
(
s
e
r
v
l
e
t
)
 
א
ו
 
ס
ט
ט
י
 
(
ד
ף
 
h
t
m
l
)
The RequestDispatcher object is used to 
send a client request
to any resource on the server
To send a request to a resource 
x
, use:
getServletContext().getRequestDispatcher(“
x
”)
Request Dispatcher Methods
ה
ר
ע
י
ו
ן
 
:
ח
ל
ו
ק
ה
 
ש
ל
 
ה
א
ת
ר
 
ל
ר
כ
י
ב
י
ם
 
 
ש
ו
נ
י
ם
ה
ע
ב
ר
ה
 
ש
ל
 
ה
ב
ק
ש
ה
 
(
h
t
t
p
 
r
e
q
u
e
s
t
)
 
ל
ט
י
פ
ו
ל
 
s
e
r
v
l
e
t
 
 
א
ח
ר
:
ס
מ
ס
ט
ר
 
א
׳
:
 
E
q
u
i
v
a
l
e
n
t
 
t
o
 
t
h
e
 
3
r
d
 
p
a
r
a
m
e
t
e
r
 
(
n
e
x
t
)
 
o
f
 
a
 
r
o
u
t
e
 
i
n
 
n
o
d
e
J
S
void 
forward
(ServletRequest request, ServletResponse response)
Forwards a request from a servlet to another resource (servlet)
Note: forward from doGet()/doPost() sends to doGet()/doPost()
ש
י
מ
ו
ש
 
ב
-
s
e
r
v
l
e
t
 
א
ח
ר
 
ע
ל
 
מ
נ
ת
 
ל
י
צ
ו
ר
 
ח
ל
ק
 
מ
ה
ת
ש
ו
ב
ה
 
(
h
t
t
p
 
r
e
s
p
o
n
s
e
)
ה
ד
ף
 
מ
ח
ו
ל
ק
 
ל
ח
ל
ק
י
ם
 
ל
צ
ו
ר
ך
 
ש
י
מ
ו
ש
 
ח
ו
ז
ר
void 
include
(ServletRequest request, ServletResponse response)
Includes the content of a resource in the response
26
include
include(req,res)
include(req,res)
include(req,res)
include(req,res)
http response
http request
/Shop
Browser still points to: /Shop
Do NOT
close the
response
stream
here!
Why?
Usually set
HEADERS
here and
CLOSE
response
stream here
In java
out = response.getWriter();
RequestDispatcher rd = request.getRequestDispatcher(
"/header.html"
);
rd.include(request, response);
rd = request.getRequestDispatcher(
"/userdetails"
);  
// a servlet returning some HTML
rd.include(request, response);
// note that you can out.write() anywhere here too!
rd = request.getRequestDispatcher(
"/shoppingcart"
); 
// a servlet returning some HTML
rd.include(request, response);
rd = request.getRequestDispatcher(
"/footer.html"
);
rd.include(request, response);
out.close();  
// make sure to close ONLY AT THE END!!!
forward
http response
http request
forward(req,res)
forward(req,res)
forward(req,res)
/Checkout
Browser still points to: /Checkout
Dispatcher
Servlet
(מנתב)
ח
ל
ו
ק
ה
 
ל
s
e
r
v
l
e
t
s
 
ש
ו
נ
י
ם
:
כ
ל
 
א
ח
ד
 
א
ח
ר
א
י
 
ע
ל
מ
ש
י
מ
ה
 
ס
פ
צ
י
פ
י
ת
Usually the
LAST servlet
in the
« chain » is
the one
closing the
response
stream
Common mistakes
Closing the response stream in a Servlet that was included
Closing the response stream before forwarding the request  to
another Servlet
Setting the headers (setContentType()) AFTER we already sent
data in the response: for example after inside an included
Servlet while we already wrote back HTML to the client
31
שיטות עברת נתונים
א
י
ך
 
מ
ע
ב
י
ר
י
ם
 
נ
ת
ו
נ
י
ם
 
ב
י
ן
 
s
e
r
v
l
e
t
s
?
 
י
ש
 
3
 
ד
ר
כ
י
ם
 
(
א
ג
ב
 
ל
מ
ה
 
ל
א
 
ב
-
?
c
o
o
k
i
e
s
)
Data that will be used 
only for this request
:
request
.setAttribute(
"key"
, value);
Here you can pass for example form input to be processed
Data will be used 
for this client 
(also for future requests 
 one session = one
client or user):
session
.setAttribute(
"key"
, value);
Here you can store for example a shopping cart
Data that will be used in the future 
for any client 
(the context is shared by all
users of the website)
context
.setAttribute(
"key"
, value);
Here you can put for example a counter of visitors.
32
Redirect
 (חזרה)
ה
ק
פ
צ
ה
 
ל
כ
ת
ו
ב
ת
 
U
R
L
כ
פ
ו
ל
 
2
 
מ
ס
פ
ר
 
ה
-
h
t
t
p
 
r
e
q
u
e
s
t
/
r
e
s
p
o
n
s
e
"
ש
ו
כ
ח
י
ם
"
 
מ
כ
ל
 
ה
פ
ר
מ
ט
ר
י
ם
 
ש
ל
 
ה
-
r
e
q
u
e
s
t
נ
ו
ש
א
 
ז
ה
 
נ
ל
מ
ד
 
ב
ס
מ
ס
ט
ר
 
א
׳
What are the advantages of having only one URL?
SendRedirect triggers a second HTTP request from the browser
Therefore you must use session/cookies if you need to pass data from another
page
Difference forward/redirect
object
object
Servlets in one picture
34
Web Server
+
Servlet container
Servlet A
Servlet B
thread
thread
Servlet C
thread
request
response
session
session
website
object
request.setAttribute(..) // addd extra params
dispatcher.forward(request, response) // forward to other servlet
cookies
session.setAttribute(…)
session.getAttribute(…)
response.addCookie(…)
request.getCookies()
cookies
object
object
object
Servlet Lifecycle
1.
The Servlet container calls the no-arg constructor.
2.
The Servlet container calls the init() method. This method initializes
the servlet and must be called before life of a servlet, the init()
method is called only once.
3.
After initialization, the servlet can service client requests. Each
request is serviced in its own separate thread. The Web container
calls the service() method of the servlet for every request.
4.
Finally, the Servlet container calls the destroy() method that takes
the servlet out of service. The destroy() method, like init(), is called
only once in the lifecycle of a servlet.
The Servlet
container
maintains a
bounded pool of
worker threads
to handle
requests.
Your code
tomcat
users
tomcat
More material
Link to an online excellent tutorial:
https://www.tutorialspoint.com/servlets/index.htm
Slide Note
Embed
Share

Exploring the concepts of cookies and sessions in servlets, including how cookies work, managing cookies in servlets, and an example servlet code for handling user input using cookies. Learn about the basics of servlets and how they interact with client-side cookies to enhance web application functionality.

  • Servlets
  • Cookies
  • Sessions
  • Managing Cookies
  • Web Development

Uploaded on Oct 08, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Servlets (part 2) Dr Solange Karsenty Hadassah Academic College

  2. ? (1) Cookies - (2) Session - (3) (4) ? servlets - servlet ? Chaining Servlets RequestDispatcher (include/forward, difference redirect)

  3. - (1) Cookies http , / : Cookies http : Cookies are private to each website: cookies of website x.y.com are not readable by z.com and vice versa. Within a website, cookies can be associated to a folder. It will be available to all pages in that folder and subdirectories (you can hide cookies from parent folders). Cookies are used for non-sensitive information (do not store credit cards) because the cookies file is readable on your computer You can manually delete cookies in your browser (in settings) Cookies length is limited; it cannot be used to store long information (around 4Kb, you can check on your browser the limit) Cookies can have an expiration date: these will be automatically erased at the expiration date (for example you may want to forget stored user information after a month). Cookies can be created, read and updated on the client side (with Javascript) AND on the server side (PHP, Java, javascript etc). So how does code on the server side read/write cookies that are stored on the client? Because: All cookies are sent to the server and back to the browser for each new http request (whenever you access a URL, click on a link, submit a form, or when you perform an Ajax call). All cookies are sent to the server and attached back to the page returned to the browser and the browser updates cookies (this is how the server can write cookies). 3

  4. Managing Cookies Get the cookies from the service request: Cookie[]HttpServletRequest.getCookies() Add a cookie to the service response: HttpServletResponse.addCookie(Cookie cookie) Cookie getter methods: getName(), getValue(), getPath(), getDomain(), getMaxAge, getSecure Cookie setter methods: setValue() , setPath(), setDomain() 4

  5. Example <html> <head> <title>Login Page</title> </head> <body> <h1>Logon to My Site</h1> <form action="/WelcomeBack" method="get"> Your Name: <input type="text" name="username"> <input type="submit"> </form> </body> </html> File login.html 5

  6. public class WelcomeBack extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String user = req.getParameter("username"); if (user == null) { // see (3) Cookie[] cookies = req.getCookies(); for (int i = 0 ; cookies!=null && i < cookies.length ; i++) if (cookies[i].getName().equals("username")) user = cookies[i].getValue(); } else // user filled the name in the form res.addCookie(new Cookie("username", user)); // see (2) // here we are in in the case user never filled the form so we send him // to the login page res.sendRedirect("/dbi-servlets/login.html"); } } } if (user != null) // see (2) res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html><body><h1>Welcome Back " + user + " </h1></html></body>"); } else { 6

  7. (1) This page is a static HTML page with a form to call the WelcomeBack Servlet 7

  8. (2) This page is the response of the WelcomeBack Servlet after the user has pressed the submit button. This is a GET request: the parameters from the form are appended in the request URL. The Servlet method doGet() is called. 8

  9. (3) This page is the response of the WelcomeBack Servlet when one enters the URL http:// /WelcomeBack in the brower and hits return: This is a simple GET request sent to the Servlet without any parameters. The Servlet method doGet() is called. In this example, the user previously entered his name with the form so it is read by the servlet and displayed. 9

  10. (2) Sessions () , session ID ) session session ID http session- ( : session expiration time . . 10

  11. Accessing the Session Data Session data is represented by the class HttpSession Use the methods getSesssion() or getSession(true) of the doGet/doPost/doXXX request to get the current HttpSession object, or to create one if it doesn t exist Use getSession(false) if you do not want to create a new session if no session exists 11

  12. HttpSession Methods Session Strings Cookies - ) ( Attributes Session data is accessed in a hash-table fashion: - setAttribute(String name,Object value) - ? - Object getAttribute(String name) More methods: - removeAttribute, getAttributeNames - Invalidate - isNew, getId - getCreationTime, getLastAccessedTime - getMaxInactiveInterval, setMaxInactiveInterval ) ( 12

  13. : In the following example a basic shopping cart for an online store is implemented The application consists of two Servlets: - Store.java: the main store site - ShoppingCart.java: handles cart manipulation - Each servlet handles different pages, depending on the shopping cart content and if the user already visited the store or not - In general, a servlet handles multiple pages corresponding to different states of website 13

  14. (1) This is displayed by the Store servlet as the user enters the http:// /Store URL in the browser and hits return. A GET request is sent to the Servlet. The user never visited before and no shopping cart object exists yet in the session. 14

  15. (2) This is displayed by the ShoppingCart servlet as the user hits the submit button of previous page. 15

  16. (3) This is displayed by the Store servlet as the user enters the http:// /Store URL in the browser and hits return. A GET request is sent to the Servlet. The user has a non empty shopping cart displayed by the servlet. 16

  17. (4) This is displayed by the ShoppingCart servlet as the user enters http://../ShoppingCart in the browser and hits return.S GET request is sent without any parameters. 17

  18. public class Store extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<HTML><HEAD><LINK rel='stylesheet' type='text/css href= 'cartstyle.css'></HEAD><BODY>"); HttpSession session = req.getSession(); List itemList = (List)session.getAttribute("item-list"); if(itemList==null) { out.println("Hello new visitor!<br><br>"); itemList = new LinkedList(); session().setAttribute("item-list", itemList); } for(Iterator it = itemList.iterator(); it.hasNext();) out.println("<LI>"+it.next()+"</LI>"); out.println("</I></OL>"); out.println("<FORM method='POST' action= ShoppingCart'>Add item:<INPUT name='item' type='text'>" + "<INPUT type='submit' value='send'><BR><BR><INPUT type='submit' value='Empty Cart' name='clear'>" + "</FORM></BODY></HTML>"); out.close(); } } out.println("Your Shopping Cart:<OL><I>"); 18

  19. public class ShoppingCart extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<HTML><HEAD><LINK rel='stylesheet type='text/css' href='cartstyle.css'></HEAD><BODY>"); List items = (List)req.getSession().getAttribute("item-list"); if (req.getParameter("clear")!= null) { // user hit the empty cart button (button name= clear ) items.clear(); out.println("Your Shopping Cart is Empty!"); } else { // user hit submit and added an item to cart String item = req.getParameter("item"); items.add(item); out.println("The item <I>" + item + "</I> was added to your cart."); } out.println("<BR><BR><A HREF='Store'> return to store</A>"); out.println("</BODY></HTML>"); // it s important close = to signal the browser we are finished sending the output out.close(); } } 19

  20. (3) ServletContext ServletContext object Can store Web application initialization parameters Servlet container ) ( in ServletContext.getInitParameters Can store and manipulate application-shared attributes - servlets ) ( in ServletContext.get/setAttribute Can be used to access the logger web )! ( stdout debugging Can be used to dispatch requests to other resources 20

  21. ServletContext Methods Access initialization parameters: getInitParameter(String name), getInitParameterNames() // paramscan be defined with the @WebInitParam annotation Web-application attributes: getAttribute(String name), getAttributeNames() setAttribute(String, Object), removeAttribute(String) Transform context-relative paths to absolute paths: getRealPath(String path), URL getResource(String path) 21

  22. ServletContext Methods Write to the application log: log(String msg), log(String message, Throwable exception) Get a resource dispatcher (discussed later): RequestDispatcher getRequestDispatcher(String path) Name and version of the servlet container: String getServerInfo() 22

  23. - response response Servlet 2 other servlets Html pages - response - request

  24. (4) RequestDispatcher servlet ) servlet ) ( ( html The RequestDispatcher object is used to send a client request to any resource on the server To send a request to a resource x, use: getServletContext().getRequestDispatcher( x ) 25

  25. Request Dispatcher Methods Equivalent to the 3rd parameter (next) of a route in nodeJS (http request) : : servlet : void forward(ServletRequest request, ServletResponse response) Forwards a request from a servlet to another resource (servlet) Note: forward from doGet()/doPost() sends to doGet()/doPost() ( http response void include(ServletRequest request, ServletResponse response) Includes the content of a resource in the response ) - servlet 26

  26. Browser still points to: /Shop /Shop include http request http response Usually set HEADERS here and CLOSE response stream here Shop include(req,res) include(req,res) include(req,res) include(req,res) Do NOT close the response stream here! Why? Header user details shopping cart Footer (static) (dynamic) (dynamic) (static)

  27. In java out = response.getWriter(); RequestDispatcher rd = request.getRequestDispatcher("/header.html"); rd.include(request, response); rd = request.getRequestDispatcher("/userdetails"); // a servlet returning some HTML rd.include(request, response); // note that you can out.write() anywhere here too! rd = request.getRequestDispatcher("/shoppingcart"); // a servlet returning some HTML rd.include(request, response); rd = request.getRequestDispatcher("/footer.html"); rd.include(request, response); out.close(); // make sure to close ONLY AT THE END!!!

  28. Browser still points to: /Checkout /Checkout forward http request http response Usually the LAST servlet in the chain is the one closing the response stream Dispatcher Servlet ) Checkout ShoppingCart ( ) - ( response : servlets forward(req,res) forward(req,res) authentication payment forward(req,res)

  29. Common mistakes Closing the response stream in a Servlet that was included Closing the response stream before forwarding the request to another Servlet Setting the headers (setContentType()) AFTER we already sent data in the response: for example after inside an included Servlet while we already wrote back HTML to the client

  30. ) - ? ( 3 ? servlets cookies Data that will be used only for this request: request.setAttribute("key", value); Here you can pass for example form input to be processed Data will be used for this client (also for future requests one session = one client or user): session.setAttribute("key", value); Here you can store for example a shopping cart Data that will be used in the future for any client (the context is shared by all users of the website) context.setAttribute("key", value); Here you can put for example a counter of visitors. 31

  31. ) ( Redirect URL - 2 " http request/response - request " What are the advantages of having only one URL? SendRedirect triggers a second HTTP request from the browser Therefore you must use session/cookies if you need to pass data from another page 32

  32. Difference forward/redirect

  33. Servlets in one picture cookies cookies Servlet Lifecycle 1. The Servlet container calls the no-arg constructor. 2. The Servlet container calls the init() method. This method initializes the servlet and must be called before life of a servlet, the init() method is called only once. 3. After initialization, the servlet can service client requests. Each request is serviced in its own separate thread. The Web container calls the service() method of the servlet for every request. 4. Finally, the Servlet container calls the destroy() method that takes the servlet out of service. The destroy() method, like init(), is called only once in the lifecycle of a servlet. users request response Web Server + Servlet container tomcat The Servlet container maintains a bounded pool of worker threads to handle requests. thread thread thread response.addCookie( ) request.getCookies() Servlet A Servlet B Servlet C Your code request.setAttribute(..) // addd extra params dispatcher.forward(request, response) // forward to other servlet website session.setAttribute( ) tomcat object session session object object object object session.getAttribute( ) 34 object

  34. More material Link to an online excellent tutorial: https://www.tutorialspoint.com/servlets/index.htm

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#