Transcript ppt
Servlets – Part 2
Representation and Management
of Data on the Web
1
Announcement
• I have put an excellent book on Servlets
and JSP pages at:
– ~dbi/Core-Servlets-and-JSP.pdf
2
What are Cookies used For?
• Identifying a user during an e-commerce
(or other) session
• Avoiding user-name and password
• Customizing a site
• Focusing advertising
3
Cookies
• Cookies are state information that
gets passed back and forth between
the web server and browser in HTTP
headers
A response header
Set-Cookie: NAME=VALUE; expires=DATE;
path=PATH; domain=DOMAIN_NAME; secure
A request header
Cookie: NAME=VALUE; NAME2=VALUE2; NAME3=VALUE3...
4
Problems
• A privacy threat:
– search engine can remember previous searches
– The computer that stores the cookie can allow an
access to a site for a person that is not the person
that the site recognizes
• However, cookies do not pose a security threat
5
Sharing Information
• Can two sites share the information that
they have with cookies?
• What if the two sites use images from
the same source?
6
javax.servlet.http.Cookie
• Cookies are represented with the class
Cookie in javax.servlet.http
• A cookie object can be created by the
cookie constructor
• The name and the value of the
constructor should not include: []()
= , “
/ ? @ : ;
7
Cookies
• You create cookies and then add them to
the HttpServletResponse
– public Cookie[] getCookies()
• You can get cookies from the
HttpServletRequest
– public void addCookie(Cookie)
8
Properties of Cookies
• getDomain / setDomain
– The domain for which the cookie belongs
• getMaxAge / setMaxAge
– How long (in seconds) will the cookie last
– Negative value = per-session cookie
– Default: Only exists during session
• getName
– The name of the cookie to identify it
9
Properties of Cookies
• getPath / setPath
– Defines the path for which the cookie relates
– Cookie.setPath(“/”) means that all the pages on host
will get the cookie
– Defualt: Entire host
• getSecure / setSecure
– Should the cookie be sent with SSL secured line
• getValue / setValue
– The value that the cookie holds*
10
<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>
HTML Page
11
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;
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 ; 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>Welcome Back" + user + "</html></body>");
} else {
res.sendRedirect("/dbi/login.html");
} }}
12
Session Tracking
• HTTP is a stateless protocol
• Many web applications (i.e. shopping carts)
are not stateless)
• Need to keep track of each user’s state
(i.e. items in the shopping cart)
• Sessions can be managed using: cookies,
hidden form fields or URL rewriting
13
Using Cookies: Intuition
sessionId
dsf39324
324jlsdf
234jksdf
789388dd
sessionData
…
…
…
…
…
…
…
…
…
…
…
…
…
…
…
…
…
…
…
…
…
…
…
…
14
Hidden Form Fields: Inutiton
<INPUT TYPE = hidden
NAME = “session”
VALUE = “…” >
• Hidden fields are just another type of input tag
for a form
• The receiving web server can’t tell the
difference between a user entered value and a
hidden form field value
• For this to work: All pages must be results of
form submission
15
URL Encoding
• Client appends some extra data to all URLs of the
session:
– http://host/path/file.html?sessionid=455hh
• You must embed all links into your site!
• If you want to embed a link in a response, and want the
link to reflect the session-id, use either (from
HttpServletResponse)
– public String encodeURL(String url)
– public String encodeRedirectURL(String url)
• These encode the session id as ?name=value on the end
of the url
16
Tracking with HttpSession
• Servlets have built-in session tracking
• Every user has a HttpSession object to store
and retrieve user information, e.g.,
– shopping cart contents,
– database connections
• Can be implemented using cookies/URL Encoding
(for us it doesn’t make a difference which)
17
Getting the Session
• Retrieve the user’s session: (from the request
object) HttpSession getSession(boolean create)
• if the user has no valid session,
– a new one is created if create is true;
– null is returned if create is false
• HttpSession's method isNew() returns true if
the session is new to the client
18
Session Tracking API
• Add data to a session using HTTPSession's
method:
void setAttribute(String name, Object val)
– value must implement Serializable interface
– replaces any object that is bound in the session and
has the same name
• Retrieve data from a session
public Object getAttribute(String name)
– returns null if no object is bound to the name
19
More on Tracking API
• Retrieve the name of all session objects
– public Enumeration getAttributeNames()
• Remove an attribute from the session
– public void removeAttribute(String name)
– does nothing if no object is bound
• You can get the identifier of the object by
– public String getId(String name)
• These methods throw an IllegalStateException
if the session is invalid
20
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;
public class HitCount extends HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
HttpSession session = req.getSession(true);
Integer count = (Integer)session.getValue("tracker.count");
if (count == null) count = new Integer(1);
else count = new Integer(count.intValue() + 1);
session.putValue("tracker.count", count);
out.println("<HTML><BODY>You've visited this page " +
count + ((count.intValue() == 1) ? " time." : " times.") +
"</BODY></HTML>");
}}
21
Note about HTTPSession
• There is a single session per user, per
session.
• Different Sevlets will get the same
HttpSession object, when calling
getSession on different
HTTPServletRequest objects during the
same session
22
ServletContext
• For sharing resources among servlets in the
same web application, we use ServletContext
• Can store web application initialization
parameters (similar to ServletConfig)
• Can store attributes (defined during lifetime of
application)
• Access to logger
• Dispatching requests to other Servlets
23
ServletContext Methods
• Get a ServlerContext using getServletContext().
This is a method of Servlet
• Partial Method List:
– public void log(String msg)
– public void log(String msg, Throwable exception)
– public String getRealPath(String path)
– public Object getAttribute(String name)
– public void setAttribute(String name, Object object)
– public void removeAttribute(String name)
– public RequestDispatcher
getRequestDistpatcher(String Name);
24
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
25
Request Dispatcher Methods
• void forward (ServletRequest request,
ServletResponse response)
– Forwards a request from a servlet to another
resource (servlet, JSP file, or HTML file) on the
server
• void include (ServletRequest request,
ServletResponse response)
– Includes the content of a resource (servlet, JSP
page, HTML file) in the response
26
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);
27
Fowarding Request Example
• Consider an online Travel Agent, as shown
here
• The Travel Servlet is called by the page
• The Travel Servlet sets some variables
• The request is then forwarded depending
on the button that the user had pressed
28
public class Travel extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
String emailAddress = request.getParameter("emailAddress");
String password = request.getParameter("password");
TravelCustomer customer =
TravelCustomer.findCustomer(password, emailAddress);
if (customer == null)
gotoPage("/travel/Accounts", request, response);
customer.setStartDate(request.getParameter("startDate"));
customer.setEndDate(request.getParameter("endDate"));
customer.setOrigin(request.getParameter("origin"));
customer.setDestination(request.getParameter ("destination"));
HttpSession session = request.getSession(true);
session.putValue("customer", customer);
29
if (request.getParameter("flights") != null) {
gotoPage("/travel/BookFlights", request, response);
} else if (request.getParameter("cars") != null) {
gotoPage("/travel/RentCars", request, response);
} else if (request.getParameter("hotels") != null) {
gotoPage("/travel/FindHotels", request, response);
} else if (request.getParameter("cars") != null) {
gotoPage("/travel/EditAccounts", request, response);
} else gotoPage("/travel/IllegalRequest", request, response);
}
private void gotoPage(String address, HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(address);
dispatcher.forward(request, response);
}
}
30
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 problems does this imply might
happen when using Forward?
31
Include
• Forwarding a request completely services
a request
• To include the result of a resource (html
page, jsp page, servlet) in our response
use the include method of
RequestDispatcher
32
Servlet Chaining
• Servlets cooperate to create content
• Multiple servlets in a chain
– request parameters supplied to first servlet
– output from each Servlet piped to the next Servlet in
the chain
– last servlet in chain sends output to client
request
Web
server
Servlet
request +
response
Servlet
request +
response
Servlet
response
33
More on Servlet Chaining
• Example use:
– Servlet #1: Translates XSQL page to XML page
– Servlet #2: Translates XML to HTML using XSL
• Can Servlet chaining be implemented using
RequestDispatcher.forward?
• Can Servlet chaining be implemented using
RequestDispatcher.include?
• How can Servlet chaining be implemented?
34
Comparison
Comparing Servlets to Other
Technologies
35
Comparing Servlets to Applets
• An Applet is a Java application, embedded in a
Web page
• Commonly used for: games, graphics, etc.
• To add an Applet to a web page, use the <applet
code=“…”> tag
• When a browser loads the Web page, the applet
byte-code is downloaded to the client box and
executed by the browser
36
Problems with Applets
• Security Restrictions: Applets cannot access
files or databases
• The Bandwidth Problem: As your applets grow in
size, the download time becomes unacceptable
• Compatibility:
– client must have a compatible browser
– If a client's browser is not compatible, s/he will not
be presented with proper content
– Thin clients do not support the whole Java API
37
Servlet Solutions
• Why don't Servlets have:
– Security restrictions?
– Bandwidth problems?
– Compatibility problems?
• What disadvantages do Servlets have
over Applets?
38
Comparing Servlets to CGI
• Common Gateway Interface (CGI): Perl 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
• Thread creation requires less time and
resources
39
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!
40