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

Slides:



Advertisements
Similar presentations
JSP and Servelets.
Advertisements

CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
Server Side Programming Common Gateway Interface (CGI): Scripts generate Web pages or other files dynamically by processing form data and returning documents.
1 CS6320 – Servlet Request Dispatcher L. Grewe 2 What is the purpose Forward a request from one servlet to another (or jsp). Forward a request from one.
Objectives Ch. D - 1 At the end of this chapter students will: Know the general architecture and purpose of servlets Understand how to create a basic servlet.
CSE 190: Internet E-Commerce Lecture 7. HTML Templates Designed to separate server side logic from HTML presentation Key features –Escapes from HTML into.
An introduction to Java Servlet Programming
1 Servlets Part 2 Representation and Management of Data on the Web.
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
JSP Java Server Pages Reference:
1 CS6320 – Servlet Cookies L. Grewe 2 What is a cookie? Name-value bindings sent by a server to a web browser and then sent back unchanged by the browser.
/ department of mathematics and computer sciencedepartment of mathematics and computer science / architecture of information systems.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Java Servlets. What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Sys Prog & Scripting - HW Univ1 Systems Programming & Scripting Lecture 15: PHP Introduction.
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
Servlets, Sessions, and Cookies Lecture 8 cs193i – Internet Technologies Summer 2004 Kelly Shaw, Stanford University.
Java Servlet Technology. Introduction Servlets are Java programs that run on a Web server, handle HTTP requests and build Web pages Servlet specification.
Servlets Pranav Maydeo. What is a Servlet ? Servlets are modules of Java code that run in a server application to answer client requests. Servlets are.
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
Chapter 5 Java Servlets. Objectives Explain the nature of a servlet and its operation Use the appropriate servlet methods in a web application Code the.
Chapter 7 Java Server Pages. Objectives Explain how the separation of concerns principle applies to JSP Describe the operation and life-cycle of a JSP.
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
Session Tracking - 2 Lec 32. Last Lecture Review  Session Tracking – why?  Need to store state – typical solutions Cookies – already learned URL Rewriting.
Web Application Development * These slides have been adapted and modified from CoreServlets course material (Marty Hall) and LUMS cs391 (Umair Javed).
Java Servlets & Java Server Pages Lecture July 2013.
Chapter 6 Server-side Programming: Java Servlets
Cookies Web Browser and Server use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website it is required to maintain.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Session Management.
Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their.
Li Tak Sing COMPS311F. A web page that counts the number of times that you have visited the page. You can try the page at:
SE-2840 Dr. Mark L. Hornick1 Servlet Threads and Sessions.
ECMM6018 Enterprise Networking for Electronic Commerce Tutorial 7
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
Introduction to Servlets. Introduction Servlet is a language to develop the server side applications, and it is also server side component. It can develop.
Slides © Marty Hall, book © Sun Microsystems Press 1 Session Tracking Core Servlets & JSP book: More.
©SoftMooreSlide 1 Session Tracking with Servlets.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
CSC 2720 Building Web Applications Managing Users' States – Cookies, URL-Rewriting, Hidden Fields and Session Management APIs.
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
Session Tracking Parts of this presentation was provided by SSE.
Introduction To HTML Dr. Magdi AMER. HTML elements.
1 Servlets Part 2 Representation and Management of Data on the Web.
How CGI and Java Servlets are Run By David Stein 14 November 2006.
 Java Server Pages (JSP) By Offir Golan. What is JSP?  A technology that allows for the creation of dynamically generated web pages based on HTML, XML,
1 Servlets – Part 2 Representation and Management of Data on the Web.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
8-Mar-16 More About Servlets Session Tracking. Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information:
1 Web Programming with Servlets & JSPs WEB APPLICATIONS – AN OVERVIEW.
Distributed Web Systems Cookies and Session Tracking Lecturer Department University.
JSP Implicit Objects CS 422 Dick Steflik.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Pre assessment Questions
Sessions.
Chapter 26 Servlets.
Client / Session Identification Cookies
Servlets and Java Server Pages
Cookies Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when later visiting the.
Knowledge Byte In this section, you will learn about:
Pre-assessment Questions
CS122B: Projects in Databases and Web Applications Winter 2019
Modified slides from Dr.Sagiv
Presentation transcript:

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

2 Servlets and Cookies

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 Cookie Transportation Web browser Web server request response put cookie...

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

6 Example1: yahoo.com Response HTTP/ OK Date: Tue, 04 May :19:02 GMT Content-Length: 43 Expires: Thu, 15 Apr :00:00 GMT Cache-Control: private Set-Cookie: B=08b858509g5mm&b=2&f=g; expires=Thu, 15 Apr :00:00 GMT; path=/; domain=.yahoo.com

7 Example: google.com Response HTTP/ Found Content-Type: text/html Proxy-Connection: close Set-Cookie: PREF=ID=3e6397d87f7e7160:LD=en:CR=2:TM= :LM= :S=98ujTaoPdeFrVcKD; expires=Sun, 17-Jan :14:07 GMT; path=/; domain=.google.com Location:

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 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 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 Login Page Logon to My Site Your Name: Example

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

14

15

16 Session Management

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 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 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 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 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 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 Session Cookies Web browser 1 Web server request Servlet id 1 response put cookie id 1 response Create Session id 1

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

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 Session Cookies Web server request Servlet id 1 response request Cookie: id 2 id 2 Session read/write Web browser 2 id 2

27 sessionIdlist

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 URL Rewriting Web browser Web server request Servlet id 1 response Create Session … …

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

35

36

37

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

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 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 Store HTML Hello new visitor! Your Shopping Cart: Add item:

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

48 The Servlet Context

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 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 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 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 The Request Dispatcher

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

59

60

61

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 else getServletContext().getRequestDispatcher ("/imagesJokesOptions.html").forward(req, res); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req,res); }

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 Images and Jokes Please Select: imagesAndJokes.html

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 Comparing Servlets to Other Technologies

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