Download presentation
Presentation is loading. Please wait.
1
1 Servlets Part 2 Representation and Management of Data on the Web
2
2 Servlets and Cookies Cookie Example
3
3 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() …
4
4 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)
5
5 An Example Insert your Name What is your name? getname.html
6
6 An Example (cont) 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)); WelcomeBack.java
7
7 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(" Welcome Back " + user + " "); } WelcomeBack.java
8
8 Session Management with Servlets
9
9 Session Cookies Web browser 1 Web server request Servlet id 1 response put cookie id 1 response Create Session id 1
10
10 Session Cookies Web browser 2 Web server request Servlet id 1 response put cookie id 2 response Create Session id 2
11
11 Session Cookies Web server request Servlet id 1 response request Cookie: id 1 id 2 Session read/write Web browser 1 id 1
12
12 Session Cookies Web server request Servlet id 1 response request Cookie: id 2 id 2 Session read/write Web browser 2 id 2
13
13 sessionId list
14
14 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
15
15 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
16
16 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
17
17 Online-Store Example 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(" " + "<link rel=\"stylesheet\" type=\"text/css\"" + " href=\"cartstyle.css\"/> "); HttpSession session = req.getSession(); if (session.getAttribute("item-list") == null) { out.println(" Hello new visitor! "); session.setAttribute("item-list", new LinkedList()); } List itemList = (List) session.getAttribute("item-list"); Store.java
18
18 Online-Store Example (cont) out.println(" Your Shopping Cart: "); for (Iterator it = itemList.iterator(); it.hasNext();) out.println(" " + it.next() + " "); out.println(" "); out.println(" Add item: " + " " + " <input type=\"submit\" value=\"empty cart\" " + "name=\"clear\"/> "); out.println(" "); } Store.java
19
19 Online-Store Example (cont) 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(" <link rel=\"stylesheet\"" + " type=\"text/css\" href=\"cartstyle.css\"/>" + " "); ShoppingCart.java
20
20 Online-Store Example (cont) 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 " + item + " was added to your cart. "); } out.println(" Return to the store "); out.println(" "); }} ShoppingCart.java
21
21 URL Rewriting Web browser Web server request Servlet id 1 response Create Session … …
22
22 URL Rewriting Web server request Servlet id 1 response request (no cookie) id 2 Session read/write Web browser 1 GET servletURL;sessID=id 1 HTTP/1.0 … …
23
23 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
24
24 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: “ "
25
25 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
26
26 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 CartInitializer web.xml
27
27 The Servlet Context
28
28 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
29
29 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)
30
30 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()
31
31 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
32
32 The Request Dispatcher
33
33 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")
34
34 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
35
35 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);
36
36 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/
37
37 Jokes and Images Images and Jokes Please Select: <input type="submit" name="joke" value="A Joke" /> <input type="submit" name="image" value="An Image" /> imagesJokesOptions.html
38
38 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); } public void doGet... }} JokesAndImages.java
39
39 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(" A Joke "); int jokeNum = ((Integer) req.getAttribute("jokeNumber")).intValue(); getServletContext().getRequestDispatcher ("/jokes/joke" + jokeNum + ".txt").include(req, res); out.println("\n "); out.println(" Back "); out.println(" "); }} Jokes.java
40
40 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
41
41 Programmatic Security with Servlets
42
42 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
43
43 An Example: Security Constraints in web.xml Firm People /login.html employees managers web.xml
44
44 FORM /login /login?fail=fail managers employees web.xml An Example: Security Constraints in web.xml
45
45 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(" Firm "); out.println(" Hello. "); String username = req.getRemoteUser(); if(username==null) { out.println(" "); out.println(" Login "); out.println(" "); return; } FirmServlet
46
46 if(req.isUserInRole("employees")) { out.println(" "); out.print(" Welcome Employee " + username + "! "); } if(req.isUserInRole("managers")) { out.println(" "); out.print(" Executive average salary: 42764NIS! "); } out.print(" Log Out "); out.println(" "); } FirmServlet
47
47 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(" Login "); if(req.getParameter("fail")!=null) out.print(" Login Failed. Try Again. "); out.println(" " + " Login: " + " Password: " + " " + " "); } LoginServlet.java
48
48 public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { this.doGet(req,res); } LoginServlet.java Login LoginServlet Login /login web.xml
49
49 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"); } EndSession.java EndSession EndSession /endsession web.xml
50
50 Filters
51
51 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
52
52
53
53 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
54
54 Example Filter FilterExample Example Filter /images/* Registering a Filter web.xml
55
55 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...
56
56 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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.