Servlets, Sessions, and Cookies Lecture 8 cs193i – Internet Technologies Summer 2004 Kelly Shaw, Stanford University.

Slides:



Advertisements
Similar presentations
J0 1 Marco Ronchetti - Basi di Dati Web e Distribuite – Laurea Specialitica in Informatica – Università di Trento.
Advertisements

1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
Technology Overview JAVA Servlets CS-611 S. Witherspoon.
J.Sant Servlets Joseph Sant Sheridan Institute of Technology.
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.
Servlets Stoney Jackson
Servlets and a little bit of Web Services Russell Beale.
An introduction to Java Servlet Programming
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
Core Servlets Chapter 3 Link for Core Servlets code: om/archive/ om/archive/
2/16/2004 Dynamic Content February 16, /16/2004 Assignments Due – Message of the Day Part 1 Due – Reading and Warmup Work on Message of the Day.
1 CS6320 – Servlet Structure and Lifecycle L. Grewe.
Comp2513 Java Servlet Basics Daniel L. Silver, Ph.D.
Servlet Session Tracking II Session API All material and examples are from
Java Server and Servlet CS616 Team 9 Kim Doyle, Susan Kroha, Arunima Palchowdhury, Wei Xu.
All You Ever Wanted To Know About Servlets But Were Afraid to Ask.
Chapter 4 Servlets Concept of Servlets (What, Why, and How) Servlet API Third-party tools to run servlets Examples of Using Servlets HTML tag with GET.
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.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
Java Servlets and JSP.
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.
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.
Servlets. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
Objectives Java Servlet Web Components
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.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Session Tracking - 2 Lec 32. Last Lecture Review  Session Tracking – why?  Need to store state – typical solutions Cookies – already learned URL Rewriting.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
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.
Java Servlets Lec 27. Creating a Simple Web Application in Tomcat.
Chapter 6 Server-side Programming: Java Servlets
Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
S ERVLETS Hits Counter 21-Nov-15. S ERVLETS - H ITS C OUNTER Many times you would be interested in knowing total number of hits on a particular page of.
Java Servlet API CGI / HTTP Concepts Java Servlet API.
All You Ever Wanted To Know About Servlets But Were Afraid to Ask.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
Session Tracking Lec 31. Revisiting Session Tracking HTTP is a stateless protocol  Every request is considered independent of every other request Many.
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:
Middleware 3/29/2001 Kang, Seungwoo Lee, Jinwon. Description of Topics 1. CGI, Servlets, JSPs 2. Sessions/Cookies 3. Database Connection(JDBC, Connection.
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.
ORIGINAL BY WENDY LIU CURRENT API: Java Servlet and JSP 1.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
Slides © Marty Hall, book © Sun Microsystems Press 1 Session Tracking Core Servlets & JSP book: More.
©SoftMooreSlide 1 Session Tracking with Servlets.
Java Servlets and Java Server Pages
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.
Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory.
How CGI and Java Servlets are Run By David Stein 14 November 2006.
S ERVLETS Form Data 19-Mar-16. F ORM P ROCESSING You must have come across many situations when you need to pass some information from your browser to.
Distributed Web Systems Java Servlets Lecturer Department University.
Java Servlets By: Tejashri Udavant..
Net-centric Computing
Sessions.
SESSION TRACKING.
Servlet.
Servlets and Java Server Pages
Servlets CEN /28/2018 Copyright 2001 Ege Consulting, Inc.
All You Ever Wanted To Know About Servlets
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Web Search Interfaces.
Presentation transcript:

Servlets, Sessions, and Cookies Lecture 8 cs193i – Internet Technologies Summer 2004 Kelly Shaw, Stanford University

Why Java Servlets Instead of CGI? Efficient, Convenient, Powerful, Portable, Secure, Inexpensive Lightweight threads instead of OS threads created Single copy of code brought into memory for all threads versus per thread Data (session state) can be stored across threads within servlet container Java is portable and secure Requires little expense once servlet container integrated with web server

Servlet Structure Java Servlet Objects on Server Side Managed by Servlet Container Loads/unloads servlets Directs requests to servlets Request → doGet() Each request is run as its own thread

Web App with Servlets HEADERS BODY Servlet doGet() … GET … Servlet Container

5 Simple Steps for Java Servlets 1. Subclass off HttpServlet 2. Override doGet(....) method 3. HttpServletRequest getParameter("paramName") 4. HttpServletResponse set Content Type get PrintWriter send text to client via PrintWriter 5. Don't use instance variables

Servlet/JSP Container Java Servlet 2.4 JavaServer Pages 2.0 Tomcat is the basis for the official reference implementation

HelloWorld.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorldExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(" "); out.println(" Hello World! "); out.println(" "); out.println(" Hello World! "); out.println(" "); }

import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class RequestHeaderExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); Enumeration e = request.getHeaderNames(); while (e.hasMoreElements()) { String name = (String)e.nextElement(); String value = request.getHeader(headerName); out.println(name + “ = “ + value); } RequestHeaderExample.java

Servlet Lifecycle (Creation) Single instance created init() method called You can override init() in your subclass of HttpServlet to do some initial code.... init() is NOT called again on further requests

Servlet Lifecycle (Service Method) On each request, the server spawns a new thread and calls service() service() checks HTTP request type and calls appropriate doXXXX (Get, Post, Put...) don't override service (unless you really know what you're doing)

Servlet Lifecycle (doGet(), doPost()) Real meat of the web app is here doPost() can call doGet(), or viceversa no doHead()... system uses headers of doGet() result

Servlet Lifecycle (destroy()) For some reason (servlet idle, etc) the server may want to remove the servlet from memory destroy() allows you to close DB connections, wrap up, etc... Don't count on destroy to write persistent state (server may crash before you ever get here!)

Accessing Request Components getParameter("param1") getCookies() => Cookie[] getContentLength() getContentType() getHeaderNames() getMethod()

Environment Variables JavaServlets do not require you to use the clunky environment variables used in CGI JavaServlets do not require you to use the clunky environment variables used in CGI Individual functions: Individual functions: PATH_INFO req.getPathInfo() PATH_INFO req.getPathInfo() REMOTE_HOSTreq.getRemoteHost() REMOTE_HOSTreq.getRemoteHost() QUERY_STRINGreq.getQueryString() QUERY_STRINGreq.getQueryString() …

Setting Response Components Set status first! setStatus(int) HttpServletResponse.SC_OK... sendError(int, String) sendRedirect(String url)

Setting Response Components Set headers setHeader(…) setContentType(“text/html”) Output body PrintWriter out = response.getWriter(); out.println("...")

J2EE API HttpServletResponse, HttpServletRequest, HttpServlet, HttpSession...

Developing Servlets (Start w/ baby steps) Install Tomcat Install Tomcat Run Tomcat Run Tomcat Run examples Run examples

Creating Your Own Servlet Write new servlet (e.g. Hi.java) Make sure Tomcat jar files are in your classpath Compile servlet (javac Hi.java) Edit web.xml Restart the Tomcat Server/Servlet Container :8080/ /servlet/Hi

Debugging use out.println to the html print to a socket on localhost...

Five Minute Break

Continuity Problem Session: A user sits down, enters a website, does some work, exits HTTP Stateless Does Keep-Alive Help?

Client vs. Server Side Client Side Store Variable=Value Bindings in HTML Page, or Cookies Server Side Store Variable=Value Bindings in DB/Server Memory Store Session ID on Client Side, to identify Client

Three Typical Solutions Cookies URL Rewriting Hidden Fields

HTTP Cookies Grab-bag Lifetime Lifetime Session – not written to file system Session – not written to file system Persistent – written to user preferences Persistent – written to user preferences Only returns cookie to requesting domain Only returns cookie to requesting domain Cookie must be specified by content Cookie must be specified by content No special characters in cookie No special characters in cookie

HTTP Cookies String sID = makeUniqueString(); Hashtable sessionInfo = new Hashtable(); Hashtable globalTable = findTableStoringSessions(); globalTable.put(sID, sessionInfo); Cookie sessionCookie = new Cookie("JSESSIONID", sID); sessionCookie.setPath("/"); response.addCookie(sessionCookie);

HTTP Cookies String sID = makeUniqueString(); Hashtable sessionInfo = new Hashtable(); Hashtable globalTable = findTableStoringSessions(); globalTable.put(sID, sessionInfo); Cookie sessionCookie = new Cookie("JSESSIONID", sID); sessionCookie.setPath("/"); response.addCookie(sessionCookie);

HTTP Cookies String sID = makeUniqueString(); Hashtable sessionInfo = new Hashtable(); Hashtable globalTable = findTableStoringSessions(); globalTable.put(sID, sessionInfo); Cookie sessionCookie = new Cookie("JSESSIONID", sID); sessionCookie.setPath("/"); response.addCookie(sessionCookie);

HTTP Cookies String sID = makeUniqueString(); Hashtable sessionInfo = new Hashtable(); Hashtable globalTable = findTableStoringSessions(); globalTable.put(sID, sessionInfo); Cookie sessionCookie = new Cookie("JSESSIONID", sID); sessionCookie.setPath("/"); response.addCookie(sessionCookie);

HTTP Cookies String sID = makeUniqueString(); Hashtable sessionInfo = new Hashtable(); Hashtable globalTable = findTableStoringSessions(); globalTable.put(sID, sessionInfo); Cookie sessionCookie = new Cookie("JSESSIONID", sID); sessionCookie.setPath("/"); response.addCookie(sessionCookie); JSESSIONID →

HTTP Cookies String sID = makeUniqueString(); Hashtable sessionInfo = new Hashtable(); Hashtable globalTable = findTableStoringSessions(); globalTable.put(sID, sessionInfo); Cookie sessionCookie = new Cookie("JSESSIONID", sID); sessionCookie.setPath("/"); response.addCookie(sessionCookie); JSESSIONID → PATH → /

HTTP Cookies String sID = makeUniqueString(); Hashtable sessionInfo = new Hashtable(); Hashtable globalTable = findTableStoringSessions(); globalTable.put(sID, sessionInfo); Cookie sessionCookie = new Cookie("JSESSIONID", sID); sessionCookie.setPath("/"); response.addCookie(sessionCookie); Set-Cookie: JSESSIONID= ; path=/;

HTTP Cookies // On request String sID = request.getCookie("JSESSIONID"); Hashtable globalTable = findTableStoringSessions(); Hashtable sInfo = (Hashtable) globalTable.get(sID); Cookie: JSESSIONID= ;

HTTP Cookies // On request String sID = request.getCookie("JSESSIONID"); Hashtable globalTable = findTableStoringSessions(); Hashtable sInfo = (Hashtable) globalTable.get(sID); Cookie: JSESSIONID= ;

HTTP Cookies // On request String sID = request.getCookie("JSESSIONID"); Hashtable globalTable = findTableStoringSessions(); Hashtable sInfo = (Hashtable) globalTable.get(sID); Cookie: JSESSIONID= ;

In-Browser Cookie Management

URL Rewriting Rewrite all URLs in response to contain SessionID Parse out session ID from request line encodeURL() in HttpResponse object will rewrite session-id onto URL Limitations Always include ?sessionID= e.g. home.html/

URL Rewriting

Hidden Form Fields

Java Servlet Solution Session tracking API built on top of URL rewriting or cookies Look up HttpSession object associated with current request (or create new one) All cookie/URL rewriting mechanics hidden Look up information associated with a session Associate information with a session

Look up Session Info HttpSession session = request.getSession(true); ShoppingCart sc = (ShoppingCart) session.getAttribute("shoppingCart"); if (cart == null) { cart = new ShoppingCart(); session.setAttribute("shoppingCart", cart); }... // do something with your shopping cart object

HttpSession Methods public String getId() public boolean isNew() public long getCreationTime() public long getLastAccessedTime() public int getMaxInactiveInterval() public void setMaxInactiveInterval(int secs) public void invalidate()

Associate Info w/ Session HttpSession session = request.getSession(true); session.setAttribute("referringPage", request.getHeader("Referer")); ShoppingCart cart = (ShoppingCart)session.getAttribute("previousItems"); if (cart == null) { cart = new ShoppingCart(); session.setAttribute("previousItems", cart); } String itemID = request.getParameter("itemID"); if (itemID != null) { cart.addItem(Catalog.getItem(itemID)); }

Session Termination Automatic! After a long enough interval (getMaxInactiveInterval)

Session Tracking Amazon Servlet Container Session ID = 123XYZ Shopping Cart sc [item 1=324] Request

Session Tracking Amazon Servlet Container Session ID = 123XYZ Shopping Cart sc [item 1=324] Response: Set-Cookie: sid=123XYZ

Session Tracking Amazon Servlet Container Session ID = 123XYZ Shopping Cart sc [item 1=324] Request: Set-Cookie: sid=123XYZ

Session Tracking Amazon Servlet Container Session ID = 123XYZ Shopping Cart sc [item 1=324 item 2=115] Request: Set-Cookie: sid=123XYZ