Transcript ppt

Servlets
Part 2
Representation and Management of
Data on the Web
1
Servlets and Cookies
Cookie Example
2
Servlets and Cookies
• Java Servlet API provides comfortable mechanisms to
handle cookies
• The class javax.servlet.http.Cookie represents a
cookie
- Getter methods:
• getName(), getValue(), getPath(),
getDomain(), getMaxAge(), getSecure()…
- Setter methods:
• setValue(), setPath(), setDomain(),
setMaxAge()…
3
Servlets and Cookies (cont)
• Get the cookies from the service request:
Cookie[] HttpServletRequest.getCookies()
• Add a cookie to the service response:
HttpServletResponse.addCookie(Cookie cookie)
4
An Example
getname.html
<html>
<head><title>Insert your Name</title></head>
<body> <h1>What is your name?</h1>
<form action="welcomeback" method="get">
<p>
<input type="text" name="username" />
<input type="submit" />
</p>
</form>
</body>
</html>
5
An Example (cont)
WelcomeBack.java
public class WelcomeBack extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String user = req.getParameter("username");
if (user == null) { // Find the "username" cookie
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));
6
An Example (cont)
if (user == null) // No parameter and no cookie
res.sendRedirect("getname.html");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<html><body><h1>Welcome Back " + user
+ "</h1></body></html>");
}
}
WelcomeBack.java
7
Session Management with
Servlets
8
Session Cookies
request
id1
Web
browser 1
request
Servlet
put cookie id1
response
id1
response
Create Session
Web server
9
Session Cookies
request
id2
Web
browser 2
request
put cookie id2
response
Servlet
id2
id1
response
Create Session
Web server
10
Session Cookies
request
request
Cookie: id1
id1
Web
browser 1
Servlet
id2
response
id1
Web server
response
Session
read/write
11
Session Cookies
request
request
Cookie: id2
id2
Web
browser 2
Servlet
id2
response
id1
Web server
response
Session
read/write
12
sessionId
list
13
Accessing the Session Data
• The session object 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
- When a new session is created, the server automatically add a
session cookie to the response
• Use getSession(false) if you do not want to create a
new session when no session exists
14
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
15
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
16
Online-Store Example
Store.java
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();
if (session.getAttribute("item-list") == null) {
out.println("<h1>Hello new visitor!</h1>");
session.setAttribute("item-list", new LinkedList());
}
17
List itemList = (List) session.getAttribute("item-list");
Online-Store Example (cont)
out.println("<h2>Your Shopping Cart:</h2><ol>");
for (Iterator it = itemList.iterator(); it.hasNext();)
out.println("<li>" + it.next() + "</li>");
out.println("</ol>");
out.println("<form method=\"post\" action=\"cart\">");
out.println("<p>Add item:<input name=\"item\" type=\"text\"/>"
+ "<input type=\"submit\" value=\"send\"/></p>"
+ "<p><input type=\"submit\" value=\"empty cart\" "
+ "name=\"clear\"/></p></form>");
out.println("</body></html>");
}
}
Store.java
18
Online-Store Example (cont)
ShoppingCart.java
public class ShoppingCart extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse
res) throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
List items = (List) req.getSession().getAttribute("item-list");
out.println("<html><head><link rel=\"stylesheet\""
+ " type=\"text/css\" href=\"cartstyle.css\"/>"
+ "</head><body>");
19
Online-Store Example (cont)
if (req.getParameter("clear") != null) {
items.clear();
out.println("<h2>Your Shopping Cart is Empty!</h2>");
} else {
String item = req.getParameter("item");
items.add(item);
out.println("<h2>The item <i>" + item +
"</i> was added to your cart.</h2>");
}
out.println("<h2><a href=\"store\">Return to the store</a></h2>");
out.println("</body></html>");
}}
ShoppingCart.java
20
URL Rewriting
request
request
Servlet
response
Web
browser
id1
response
Create Session
Web server
<HTML>…
<A HREF=“servletURL;sessID=id1”>
…</HTML>
21
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>
22
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
23
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("cart") + "\">"
• ShoppingCart.java:
“<a href=\"" + res.encodeURL("store") + "\">"
24
The Session Listener
• The session listener reacts to the following
events:
- A new session has been created
- A session is being destroyed
• To obtain a session listener, implement the
interface javax.servlet.http.HttpSessionListener
25
Session-Listener Example (cont)
public class CartInitializer implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent se) {
List itemList = new LinkedList();
se.getSession().setAttribute("item-list",itemList);
itemList.add("A Free Apple");
}
public void sessionDestroyed(HttpSessionEvent se) {}
}
CartInitializer.java
<listener>
<listener-class>CartInitializer</listener-class>
</listener>
web.xml
26
The Servlet Context
27
Uses of ServletContext
• For communicating with the Servlet container (e.g.,
Tomcat server), 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
28
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)
29
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()
30
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
31
The Request Dispatcher
32
The Request Dispather
• 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. a HTML document)
• To send a request to a resource x, use:
getServletContext().getRequestDispatcher("x")
33
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
34
Passing on Data
• 3 different ways to pass parameters for the forwarded
Servlet or JSP
- 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 every client
context.setAttribute("key", value);
35
An Example
• The Servlet JokesAndImages enables a user to choose
a random joke or a random image
• The server has 5 images in the directory images/ and
five jokes (txt files) in the directory jokes/
• Empty requests are forwarded to a HTML file that
enables the user to choose a joke or an image
• Requests to a joke are forwarded to the servlet Jokes
• Requests to an image are forwarded to a random image
from the directory images/
36
Jokes and Images
<html>
<head><title>Images and Jokes</title></head>
<body>
<h1>Please Select:</h1>
<form method="post" action="JokesAndImages">
<h2>
<input type="submit" name="joke"
value="A Joke" />
<input type="submit" name="image"
value="An Image" />
</h2>
</form>
imagesJokesOptions.html
</body></html>
37
Jokes and Images (cont)
public class JokesAndImages extends HttpServlet {
public void doPost(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);
} else getServletContext().getRequestDispatcher
("/imagesJokesOptions.html"). forward(req,res);
}
38
public void doGet ... }}
JokesAndImages.java
Jokes and Images (cont)
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>");
Jokes.java
}}
39
Forwarding versus Redirection
• SendRedirect requires extra communication on part of
the client: Why?
• By default, SendRedirect does not preserve
parameters of the request
• SendRedirect ends up with a different URL on the
client
• Which image will be loaded in the following scenario?
Servlet /a forwards to /jokes/joke1.html and
joke1.html includes <img src="image1.gif".../>
40
Programmatic Security
with Servlets
41
Programmatic-Security Methods
• Servlet API contains several accessories for handling
programmatic security:
- getRemoteUser()
- isUserInRole(String role)
- getAuthType()
• These are all methods of HttpServletRequest
• To enable user authentication (even for public URLs),
provide a link to some protected page
42
An Example: Security Constraints
in web.xml
<security-constraint>
<web-resource-collection>
<web-resource-name>Firm People</web-resource-name>
<url-pattern>/login.html</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>employees</role-name>
<role-name>managers</role-name>
</auth-constraint>
</security-constraint>
web.xml
43
An Example: Security Constraints
in web.xml
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login</form-login-page>
<form-error-page>/login?fail=fail</form-error-page>
</form-login-config>
</login-config>
<security-role>
<role-name>managers</role-name>
</security-role>
<security-role>
<role-name>employees</role-name>
web.xml
</security-role>
44
public class FirmServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse
res) throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<html><head><title>Firm</head><body>");
out.println("<h1>Hello.</h1>");
String username = req.getRemoteUser();
if(username==null) {
out.println("<p><img src=\"images/visitor.gif\"/></p>");
out.println("<h3><a href=\"login.html\">Login</a></h3>");
out.println("</body></html>");
return; }
FirmServlet
45
if(req.isUserInRole("employees")) {
out.println("<p><img src=\"images/employee.gif\"/></p>");
out.print("<h2>Welcome Employee " + username + "!</h2>");
}
if(req.isUserInRole("managers")) {
out.println("<p><img src=\"images/manager.gif\"/></p>");
out.print("<h2>Executive average salary: 42764NIS!</h2>");
}
out.print("<h3><a href=\"endsession\">Log Out</a></h3>");
out.println("</body></html>");
}
}
FirmServlet
46
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.println("<html><head><title>Login</title></head><body>");
if(req.getParameter("fail")!=null)
out.print("<h2>Login Failed. Try Again.</h2>");
out.println("<form action=\"j_security_check\" method=\"post\">" +
"<p>Login: <input type=\"text\" name=\"j_username\"/></p>" +
"<p>Password: <input type=\"password\" name=\"j_password\"/></p>" +
"<p><input type=\"submit\" value=\"Log In\"/></p>" +
"</form></body></html>");
}
LoginServlet.java
47
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
this.doGet(req,res);
}
}
LoginServlet.java
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
web.xml
48
public class EndSession extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession(false);
if(session!=null)
session.invalidate();
res.sendRedirect("firm");
}
<servlet>
}
EndSession.java
<servlet-name>EndSession</servlet-name>
<servlet-class>EndSession</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>EndSession</servlet-name>
<url-pattern>/endsession</url-pattern>
49
</servlet-mapping>
web.xml
Filters
50
Filters in Servlet API
• Filters are used to dynamically intercept requests
and responses
• A filter that applies to a URL u typically acts as
follows given a request for u
- performs some actions before the processing of u
- passes the request handling to the next filter
- performs some actions after the processing of u
51
Client
Request
Response
Container
Filter 1
Filter 2
Filter 3
Servlet/JSP/HTML
52
public final class FilterExample implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
...
}
public void destroy() {
...
}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
...
chain.doFilter(request, response);
...
}}
FilterExample.java
53
Registering a Filter
<filter>
<filter-name>Example Filter</filter-name>
<filter-class>FilterExample</filter-class>
</filter>
<filter-mapping>
<filter-name>Example Filter</filter-name>
<url-pattern>/images/*</url-pattern>
</filter-mapping>
web.xml
54
What Can we Do with Filters?
• Examine and log requests
• Modify request headers and properties
• Modify the response headers and response data
- E.g., by replacing the response with a wrapper
- Content compression
- Image conversion
• Block requests
• And more...
55
Notes About Filters
• The order of the filters in the chain is the same as the
order that filter mappings appear web.xml
• The life cycle of filters is similar to that of Servlets
• Filters typically do not themselves create responses,
although they can
• The request and response arguments of doFilter are
actually of type HttpServletRequest and
HttpServletResponse
• The filterConfig is used to read initialization parameters
- Those are set in web.xml
56