Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Servlets Part 2 Representation and Management of Data on the Web.

Similar presentations


Presentation on theme: "1 Servlets Part 2 Representation and Management of Data on the Web."— Presentation transcript:

1 1 Servlets Part 2 Representation and Management of Data on the Web

2 2 Servlets and Cookies

3 3 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

4 4 Cookie Transportation Web browser Web server request response put cookie...

5 5 Cookie Transportation Web server response request Cookie:... Web browser

6 6 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

7 7 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/

8 8 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

9 9 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)

10 10 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() …

11 11 Login Page Logon to My Site Your Name: Example

12 12 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(" Welcome Back " + user + “ "); } else { res.sendRedirect("/dbi-servlets/login.html"); } } }

13 13

14 14

15 15

16 16 Session Management

17 17 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 cartOnline stores -Portals that remember your name and preferences

18 18 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?

19 19 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

20 20 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

21 21 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)

22 22 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

23 23 Session Cookies Web browser 1 Web server request Servlet id 1 response put cookie id 1 response Create Session id 1

24 24 Session Cookies Web browser 2 Web server request Servlet id 1 response put cookie id 2 response Create Session id 2

25 25 Session Cookies Web server request Servlet id 1 response request Cookie: id 1 id 2 Session read/write Web browser 1 id 1

26 26 Session Cookies Web server request Servlet id 1 response request Cookie: id 2 id 2 Session read/write Web browser 2 id 2

27 27 sessionIdlist

28 28 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

29 29 URL Rewriting Web browser Web server request Servlet id 1 response Create Session … …

30 30 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 … …

31 31 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

32 32 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

33 33 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

34 34

35 35

36 36

37 37

38 38 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(" "+" "); HttpSession session = req.getSession(); List itemList = (List)session.getAttribute("item-list"); if(itemList==null) { out.println("Hello new visitor! "); itemList = new LinkedList(); session().setAttribute("item-list", itemList); }

39 39 out.println("Your Shopping Cart: "); for(Iterator it = itemList.iterator(); it.hasNext();) out.println(" "+it.next()+" "); out.println(" "); out.println(" “ +"Add item: " + " " + " "); out.close(); }}

40 40 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(" <LINK rel=\"stylesheet\""+ " type=\"text/css\" href=\"cartstyle.css\">"+ " ");

41 41 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 " + item + " was added to your cart."); } out.println(" ” +"return to store "); out.println(" "); out.close(); }

42 42 Store HTTP Dialog GET /dbi-servlets/Store HTTP/1.1 Accept: */* Host: localhost Connection: Keep-Alive HTTP/1.1 200 OK Set-Cookie: JSESSIONID=850173A82D7A7C66B28AF6F337AF73AD; Path=/dbi Content-Type: text/html Content-Length: 402 Server: Apache-Coyote/1.1 The first request to Servlet Response:

43 43 Store HTTP Dialog GET /dbi-servlets/Store HTTP/1.1 Accept: */* Host: localhost Connection: Keep-Alive Cookie: JSESSIONID=850173A82D7A7C66B28AF6F337AF73AD HTTP/1.1 200 OK Content-Type: text/html Content-Length: 330 Server: Apache-Coyote/1.1 Next request to Store: Response:

44 44 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

45 45 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: " ShoppingCart.java: “ ”

46 46 Store HTML Hello new visitor! Your Shopping Cart: Add item:

47 47 ShoppingCart HTML The item Banana was added to your cart. return to store

48 48 The Servlet Context

49 49 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

50 50 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)

51 51 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()

52 52 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

53 53 The Request Dispatcher

54 54 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”)

55 55 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

56 56 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);

57 57 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

58 58

59 59

60 60

61 61

62 62 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); }

63 63 else getServletContext().getRequestDispatcher ("/imagesJokesOptions.html").forward(req, res); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req,res); }

64 64 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(" "); }

65 65 Images and Jokes Please Select: imagesAndJokes.html

66 66 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)

67 67 Comparing Servlets to Other Technologies

68 68 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

69 69 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!


Download ppt "1 Servlets Part 2 Representation and Management of Data on the Web."

Similar presentations


Ads by Google