Transcript ppt

Servlets
Part 2
Representation and Management of
Data on the Web
1
Servlets and Cookies
2
Cookies
• Cookies are a general mechanism which server
side applications can use to both store and
retrieve information on the client side
• Servers send cookies in the HTTP response and
browsers are expected to save and to send the
cookie back to the Server whenever they make
additional requests from the Server
3
Cookie Transportation
request
put cookie ...
response
Web
browser
Web server
4
Cookie Transportation
request
Cookie: ...
response
Web
browser
Web server
5
Example1: yahoo.com Response
HTTP/1.1 200 OK
Date: Tue, 04 May 2004 22:19:02 GMT
Content-Length: 43
Expires: Thu, 15 Apr 2010 20:00:00 GMT
Cache-Control: private
Set-Cookie: B=08b858509g5mm&b=2&f=g; expires=Thu, 15
Apr 2010 20:00:00 GMT; path=/; domain=.yahoo.com
6
Example: google.com Response
HTTP/1.1 302 Found
Content-Type: text/html
Proxy-Connection: close
Set-Cookie:
PREF=ID=3e6397d87f7e7160:LD=en:CR=2:TM=10812
94885:LM=1081295099:S=98ujTaoPdeFrVcKD;
expires=Sun, 17-Jan-2038 19:14:07 GMT; path=/;
domain=.google.com
Location: http://www.google.com/
7
Cookie Format
• A cookie in a response header:
Set-Cookie: NAME=VALUE; expires=DATE; path=PATH;
domain=DOMAIN_NAME; secure
- Only the NAME field is required
• A cookie in a request header:
Cookie: NAME1=VALUE1; NAME2=VALUE2;
NAME3=VALUE3...
- This header contains all matching stored cookies
8
Cookie Properties
• NAME=VALUE: the content of the cookie
- should not contain semi-colon, comma or white-space
• expires=DATE: expiration date
- default is the session life time
• path=PATH: the paths to which the cookie is valid
- matches every path that begins with PATH
• domain=DOMAIN_NAME: the cookie’s domain
- matches every path that ends with DOMAIN_NAME
• secure: send only through secure channels (i.e. https)
9
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()…
10
Example
<html> <head>
<title>Login Page</title>
</head>
<body>
<h1>Logon to My Site</h1>
<form action="servlet/WelcomeBack">
Your Name:
<input type="text" name="username">
<input type="submit">
</form>
</body>
</html>
11
public class WelcomeBack extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String user = req.getParameter("username");
if (user == null) {
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 res.addCookie(new Cookie("username", user));
if (user != null) {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<html><body><H1>Welcome Back " + user +
“</H1></html></body>");
} else { res.sendRedirect("/dbi-servlets/login.html"); } } }
12
13
14
15
Session Management
16
HTTP is Stateless
• HTTP is a stateless protocol
- Individual requests are treated independently
- Without external support, one cannot tell whether an HTTP
request is a part of a continuing interaction between the client
and the server
• BUT some Web applications are stateful!
- Online stores that maintain a shopping cart
- Portals that remember your name and preferences
17
HTTP Sessions
• The solution: Client and Server transfer some unique
data in the course of a session
• A session captures the notion of a continuous interaction
between a server and a client
- For example, a series of requests and responses between IE
and Tomcat with short intervals between them
• Session management should be oblivious to the end-user
• Session management should be efficient
- Is it reasonable to send the whole shopping cart upon every
request to Amazon.com?
18
Session Supporting Servers
• A server that supports sessions holds the session-specific
data in an internal data structure (session object)
• Upon the first request, the server initializes the session
object and sends the client a unique key for this object
• During the session, the client attaches this key to every
request to the server
19
Session Management Methods
•
How is the session key shared between the
client and the server?
•
We will discuss two methods that Servlet
containers (i.e. Tomcat) support:
1. Session Cookies
2. URL rewriting
20
Session Cookies
• In the response to the first request of a session, the
server puts a cookie, which contains a key to the session
• When the client sends subsequent requests, it also sends
the cookie
• The browser sends the cookie as long as the requests are
in the session bound (e.g. the same process)
• The server treats the cookie as valid as long as the
requests are in the session bound (e.g. a short time
period passed since the last request)
21
Session Cookies
• Session cookies are simply a special kind of
cookies
• The time boundary of session cookies is based on
the session and not on an explicit date
- This is the default expiration time
• Session data is kept on the server, while the
session cookie holds only a key to this data
22
Session Cookies
request
request
Servlet
put cookie id1
id1
Web
browser 1
response
id1
response
Create Session
Web server
23
Session Cookies
request
request
put cookie id2
id2
Web
browser 2
response
Servlet
id2
id1
response
Create Session
Web server
24
Session Cookies
request
request
Cookie: id1
id1
Web
browser 1
Servlet
id2
response
id1
Web server
response
Session
read/write
25
Session Cookies
request
request
Cookie: id2
id2
Web
browser 2
Servlet
id2
response
id1
Web server
response
Session
read/write
26
sessionId
list
27
URL Rewriting
• Web browsers may refuse to save cookies
- Can you think of reasons?
• Therefore, Servlet containers support session
management through URL rewriting
• Instead of passing the session key in a cookie, the
key is concatenated to the request URL
• Pages should contain dynamically created links for
site navigation
- thus, users are oblivious to the session management
28
URL Rewriting
request
request
Servlet
response
Web
browser
id1
response
Create Session
Web server
<HTML>…
<A HREF=“servletURL;sessID=id1”>
…</HTML>
29
URL Rewriting
request
request
(no cookie)
Servlet
id2
response
Web
browser 1
id1
response
Web server
Session
read/write
<HTML>…
<A HREF=“servletURL;sessID=id1”>
GET servletURL;sessID=id1 HTTP/1.0
…</HTML>
30
Accessing the Session Data
• Session data is represented by the class HttpSession
• Use the methods getSesssion() or getSession(true)
of the 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
31
HttpSession Methods
• Session data is accessed in a hash-table fashion:
- setAttribute(String name,Object value)
- Where is this value stored?
- Object getAttribute(String name)
• More methods:
- removeAttribute, getAttributeNames
- isNew, invalidate, getId
- getCreationTime, getLastAccessedTime
- getMaxInactiveInterval, setMaxInactiveInterval
32
Example: A Basic Shopping Cart
• 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
33
34
35
36
37
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); }
38
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=\"SoppingCart\">“
+"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();
}}
39
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>");
40
List items = (List)req.getSession().getAttribute("item-list");
if(req.getParameter("clear")!= null) {
items.clear();
out.println("Your Shopping Cart is Empty!"); }
else {
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>");
out.close();
}}
41
Store HTTP Dialog
The first request to Servlet
GET /dbi-servlets/Store HTTP/1.1
Accept: */*
Host: localhost
Connection: Keep-Alive
Response:
HTTP/1.1 200 OK
Set-Cookie: JSESSIONID=850173A82D7A7C66B28AF6F337AF73AD; Path=/dbi
Content-Type: text/html
Content-Length: 402
Server: Apache-Coyote/1.1
42
Store HTTP Dialog
Next request to Store:
GET /dbi-servlets/Store HTTP/1.1
Accept: */*
Host: localhost
Connection: Keep-Alive
Cookie: JSESSIONID=850173A82D7A7C66B28AF6F337AF73AD
Response:
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 330
Server: Apache-Coyote/1.1
43
Servlet URL Rewriting
• Use the following methods of the doXXX response
object to rewrite URLs:
- String encodeURL(String url)
• Use for HTML hyperlinks
- String encodeRedirectURL(String url)
• Use for HTTP redirections
• These methods contain the logic to determine whether
the session ID needs to be encoded in the URL
• For example, if the request has a cookie, then url is
returned unchanged
• Some servers implement the two methods identically
44
Back to our Store
• The Store example assumes that the client supports
cookies
• To fix the program, we should encode the links we
supply:
• Store.java:
"<FORM method=\"POST\" action=\"" +
res.encodeURL(“SoppingCart”) + "\">"
• ShoppingCart.java:
“<A HREF=\"" + res.encodeURL("Store") + "\">”
45
Store HTML
<html><head><link rel="stylesheet" type="text/css"
href="cartstyle.css"></head><body>
Hello new visitor!<br><br>
Your Shopping Cart:<ol><i> </i></ol>
<form method="POST“ action=
"ShoppingCart;jsessionid=2409D7C062C6E32E2B4F28EAB1
36E7F8">
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>
46
ShoppingCart HTML
<html><head>
<link rel="stylesheet" type="text/css“
href="cartstyle.css"></head>
<body>
The item <i>Banana</i> was added to your cart.
<br><br>
<a HREF=
"Store;jsessionid=2409D7C062C6E32E2B4F28EAB136E7
F8">return to store</a>
</body></html>
47
The Servlet Context
48
ServletContext
• For communicating with the Servlet container, we use the
ServletContext object
• One context is shared among all Web-application Servlets
• Can store Web application initialization parameters
• Can store and manipulate application-shared attributes
• Can be used to access the logger
• Can be used to dispatch requests to other resources
49
ServletContext Methods
• Access initialization parameters:
getInitParameter(String name), getInitParameterNames()
• Read Web-application attributes:
getAttribute(String name), getAttributeNames()
• Manipulate Web-application attributes:
setAttribute(String, Object), removeAttribute(String)
• Transform context-relative paths to absolute paths:
getRealPath(String path), URL getResource(String path)
50
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()
51
Note about ServletContext
• There is a single ServletContext per Web
application
• Different Sevlets 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
52
The Request Dispatcher
53
RequestDispather
• The RequestDispatcher object is used to send a a
client request to any resource on the server
• Such a resource may be dynamic (e.g. a Servlet
or a JSP file) or static (e.g. HTML document)
• To send a request to a resource x, use:
getServletContext().getRequestDispatcher(“x”)
54
Request Dispatcher Methods
• void forward(ServletRequest request,
ServletResponse response)
- Forwards a request from a servlet to another resource
• void include(ServletRequest request,
ServletResponse response)
- Includes the content of a resource in the response
55
Passing on Data
• 3 different ways to set parameters for the forwarded
Servlet or JSP to see
- Data that will be used only for this request:
request.setAttribute("key", value);
- Data will be used for this client (also for future requests):
session.setAttribute("key", value);
- Data that will be used in the future for any client
context.setAttribute("key", value);
56
An Example
• The Servlet JokesAndImages enables a user to
choose a random joke or a random image
• Empty requests are forwarded to a html file
• Requests to a joke are forwarded to the servlet
Jokes
• Requests to an image are forwarded to a random
image URL
57
58
59
60
61
public class JokesAndImages extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
int randomNum = 1+Math.abs((new Random()).nextInt()%5);
if(req.getParameter("joke")!=null) {
req.setAttribute("jokeNumber", new Integer(randomNum));
getServletContext().getRequestDispatcher
("/Jokes").forward(req, res);
} else if(req.getParameter("image")!=null) {
getServletContext().getRequestDispatcher("/images/image" +
randomNum + ".gif").forward(req, res);
}
62
else
getServletContext().getRequestDispatcher
("/imagesJokesOptions.html").forward(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse
res) throws ServletException, IOException {
doGet(req,res);
}
}
63
public class Jokes extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse
res) throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML><BODY><H1>A Joke</H1><PRE>");
int jokeNum =
((Integer)req.getAttribute("jokeNumber")).intValue();
getServletContext().getRequestDispatcher
("/jokes/joke" + jokeNum +".txt").include(req, res);
out.println("\n</PRE>");
out.println("<A HREF=\""+req.getRequestURL()+"\">Back</A>");
out.println("</BODY></HTML>"); }
64
imagesAndJokes.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML> <HEAD> <TITLE>Images and Jokes</TITLE>
</HEAD> <BODY>
<CENTER> <H1>Please Select:</H1>
<FORM METHOD="POST">
<INPUT TYPE="submit" NAME="joke" VALUE="A Joke">
<INPUT TYPE="submit" NAME="image" VALUE="An Image">
</FORM>
</CENTER>
</BODY> </HTML>
65
Forward versus SendRedirect
• SendRedirect requires extra communication on part of
the client: Why?
• SendRedirect does not have to preserve all the variables
in the request
• SendRedirect ends up with a different URL on the client
- What are the advantages of having only one URL? (think of
page bookmarking, for example)
66
Comparing Servlets to Other
Technologies
67
Comparing Servlets to CGI
• Common Gateway Interface (CGI): scripts that generate
Web pages dynamically by processing form data
• With CGI, each request causes a new process to be
created that runs the script
• With Servlets, each request causes a new thread to be
created, while the Servlet instance remains on the server
• Thread creation requires less time and resources
• With Servlets, resources are more elegantly shared
among all Web-application entities
68
Java Server Pages (JSP)
• JavaServer Pages: use XML-like tags and
scriptlets written in Java within a web page
• Result in dynamic data in Web page
• JSP is automatically compiled to Servlet
• Next Week: Learn about JSP!
69