saving client state session tracking: maintain state about series of requests from same client over...

29
Saving Client State • Session Tracking: Maintain state about series of requests from same client over time • Using Cookies: Clients hold small amount of their state information. Servlets use information in cookie

Upload: abel-brooks

Post on 05-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

Saving Client State

• Session Tracking: Maintain state about series of requests from same client over time

• Using Cookies: Clients hold small amount of their state information. Servlets use information in cookie

Page 2: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

Session Tracking

• Bookstore uses to keep track of books ordered

• Obtain session object for a user (HttpSession) (boolean for creation)

• Store or get data from object

• Invalidate session

• Session properties (session identifier)

• Key-value pairs for application data

Page 3: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

Steps

• Obtain Session for a user

• Store or get data from session object

• Invalidate the session (manual or automatic)

• Bookstore uses session to keep track of books a user orders

• Shared by all servlets in application

Page 4: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;

import database.*;import cart.ShoppingCart;

/** * This is a simple example of an HTTP Servlet. It responds to the GET * and HEAD methods of the HTTP protocol. This servlet calls other * servlets. This catalog calls other servlets. */public class CatalogServlet extends HttpServlet {

public void doGet (HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException { // Get the user's session and shopping cart

//Get session before any output written to responseHttpSession session = request.getSession(true);ShoppingCart cart = (ShoppingCart)session.getValue(session.getId());

// If the user has no cart, create a new one if (cart == null) { cart = new ShoppingCart(); session.putValue(session.getId(), cart); }

// set content-type header before accessing the Writer response.setContentType("text/html"); PrintWriter out = response.getWriter();

// then write the data of the response out.println("<html>" + "<head><title> Book Catalog </title></head>" +

"<body bgcolor=\"#ffffff\">" + "<center>" + "<hr> <br> &nbsp;" + "<h1>" + "<font size=\"+3\" color=\"red\">Duke's </font>" + "<font size=\"+3\" color=\"purple\">Bookstore</font>" + "</h1>" + "</center>" + "<br> &nbsp; <hr> <br> &nbsp;");

Page 5: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

//Data on the books are from the database servlet BookDBServlet database = (BookDBServlet)

getServletConfig().getServletContext().getServlet("bookdb");

// Additions to the shopping cart String bookToAdd = request.getParameter("Buy"); if (bookToAdd != null) { BookDetails book = database.getBookDetails(bookToAdd);

cart.add(bookToAdd, book); out.println("<p><h3>" + "<font color=\"#ff0000\">" + "You just added <i>" + book.getTitle() + "</i>"+ "to your shopping cart</font></h3>"); }

//Give the option of checking cart or checking out if cart notempty if (cart.getNumberOfItems() > 0) { out.println("<table><tr>" + "<th align=\"left\"><a href=\"" + response.encodeUrl("/servlet/showcart") + "\"> Check Shopping Cart</a></th>" +

"<th>&nbsp;</th>" +

"<th align=\"right\"><a href=\"" + response.encodeUrl("/servlet/cashier") + "\"> Buy your Books</a></th>" + "</tr></table"); }

// Always prompt the user to buy more -- get and show thecatalog out.println("<br> &nbsp;" + "<h3>Please choose from our selections</h3>" + "<center> <table>");

BookDetails[] books = database.getBooksSortedByTitle(); int numBooks = database.getNumberOfBooks(); for(int i=0; i < numBooks; i++) { String bookId = books[i].getBookId();

Page 6: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import cart.ShoppingCart;

/** * An HTTP servlet that responds to the POST method of the HTTP protocol. * It clears the shopping cart, thanks the user for the order, * and resets the page to the BookStore's main page. */

public class ReceiptServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException { // Get the user's session and shopping cart HttpSession session = request.getSession(true); ShoppingCart cart = (ShoppingCart)session.getValue(session.getId());

// If the user has no cart, create a new one if (cart == null) { cart = new ShoppingCart(); session.putValue(session.getId(), cart); }

// Payment received -- invalidate the session session.invalidate();

// set content type header before accessing the Writer response.setContentType("text/html"); PrintWriter out = response.getWriter();

Page 7: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

Handling All Browsers

• Session Tracking uses cookies by default to associate session id with user

• If browser doesn’t support cookies, must use URL rewriting (not supported by servletrunner)

• Session Id included in links: session id sent as part of URL

Page 8: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

public class CatalogServlet extends HttpServlet {

public void doGet (HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException { // Get the user's session and shopping cart, the Writer, etc. ...

// then write the data of the response out.println("<html>" + ...); ... // Get the catalog and send it, nicely formatted BookDetails[] books = database.getBooksSortedByTitle(); ... for(int i=0; i < numBooks; i++) { ... //Print out info on each book in its own two rows out.println("<tr>" + ...

"<a href=\"" + response.encodeUrl("/servlet/bookdetails?bookId=" + bookId) + "\"> <strong>" + books[i].getTitle() + " </strong></a></td>" + ...

"<a href=\"" + response.encodeUrl("/servlet/catalog?Buy=" + bookId) + "\"> Add to Cart </a></td></tr>" +

} } }

Page 9: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

Using Cookies

• Key-value pair

• Way for server to store information on client

• Server appends to HTTP response headers

• Client appends to HTTP request headers

• Cookies are single-valued

Page 10: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

Procedure

• To send Cookie– Instantiate Cookie Object– Set attributes– send the cookie

• Get information from Cookie– Retrieve all cookies from the user’s request– Find cookie with name interested in– Get values from cookies

Page 11: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

Cookie Drawbacks

• Can only be strings

• take up client disk space

• browsers limit their number and size

Page 12: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

public void doGet (HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException { BookDBServlet database = (BookDBServlet) getServletConfig().getServletContext().getServlet("bookdb");

// Check for pending adds to the shopping cart String bookId = request.getParameter("Buy");

//If the user wants to add a book, remember it by adding a cookie if (bookId != null) { Cookie getBook = new Cookie("Buy", bookId); ... }

// set content-type header before accessing the Writer response.setContentType("text/html");

// now get the writer and write the data of the responsePrintWriter out = response.getWriter();

out.println("<html>" + "<head><title> Book Catalog </title></head>" + ...); ... }

Page 13: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

public void doGet (HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException { ... //If the user wants to add a book, remember it by adding a cookie if (values != null) { bookId = values[0]; Cookie getBook = new Cookie("Buy", bookId); getBook.setComment("User wants to buy this book " + "from the bookstore."); } ... }

Page 14: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

public void doGet (HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

... /* Handle any pending deletes from the shopping cart */ String bookId = request.getParameter("Remove"); ... if (bookId != null) { // Find the cookie that pertains to the book to remove ... // Delete the cookie by setting its maximum age to zero thisCookie.setMaxAge(0); ... }

// also set content type header before accessing the Writer response.setContentType("text/html"); PrintWriter out = response.getWriter();

//Print out the response out.println("<html> <head>" + "<title>Your Shopping Cart</title>" + ...);

Page 15: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

public void doGet (HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException { ... //If the user wants to add a book, remember it by adding a cookie if (values != null) { bookId = values[0]; Cookie getBook = new Cookie("Buy", bookId); getBook.setComment("User has indicated a desire " + "to buy this book from the bookstore."); response.addCookie(getBook); } ... }

Page 16: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

public void doGet (HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

...

/* Handle any pending deletes from the shopping cart */ String bookId = request.getParameter("Remove"); ... if (bookId != null) { // Find the cookie that pertains to the book to remove Cookie[] cookies = request.getCookies(); ...

// Delete the book's cookie by setting its maximum age to zero thisCookie.setMaxAge(0); }

// also set content type header before accessing the Writer response.setContentType("text/html"); PrintWriter out = response.getWriter();

//Print out the response out.println("<html> <head>" + "<title>Your Shopping Cart</title>" + ...);

Page 17: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

public void doGet (HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException { ... /* Handle any pending deletes from the shopping cart */ String bookId = request.getParameter("Remove"); ... if (bookId != null) { // Find the cookie that pertains to that book Cookie[] cookies = request.getCookies(); for(i=0; i < cookies.length; i++) { Cookie thisCookie = cookie[i]; if (thisCookie.getName().equals("Buy") && thisCookie.getValue().equals(bookId)) {

// Delete the cookie by setting its maximum age to zero thisCookie.setMaxAge(0); } } }

// also set content type header before accessing the Writer response.setContentType("text/html"); PrintWriter out = response.getWriter();

//Print out the response out.println("<html> <head>" + "<title>Your Shopping Cart</title>" + ...);

Page 18: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

import java.io.*;import java.net.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;

public class CookieCounterServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html");

PrintWriter out = response.getWriter();

Cookie cookies[] = request.getCookies(); int i,max=0; String countStr=null; String createStr = null; Cookie curCookie=null; Cookie countCookie=null;

if(cookies != null) max = cookies.length;

for(i=0;i<max;i++) { curCookie = cookies[i];

if("count".equals(curCookie.getName())) { countStr = curCookie.getValue(); countCookie = curCookie; } else if("create".equals(curCookie.getName())) { createStr = URLDecoder.decode(curCookie.getValue()); //Don't change just re-add response.addCookie(curCookie); } else {

response.addCookie(curCookie); } }

Page 19: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

//Set the cookie first since it goes in the header if((countStr == null)||(countCookie == null)) { countStr = "0"; curCookie = new Cookie("count",countStr); response.addCookie(curCookie);

createStr = (new Date()).toString(); createStr = URLEncoder.encode(createStr);

curCookie = new Cookie("create" ,createStr);

createStr = URLDecoder.decode(createStr); response.addCookie(curCookie); } else { int intCount=0;

intCount = Integer.parseInt(countStr) + 1; countStr = String.valueOf(intCount); countCookie.setValue(countStr);

response.addCookie(countCookie); }

out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("Cookie Counter Servlet"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY>");

out.println("The count is set to "+countStr+"."); out.println("<BR>"); out.println("The creation time was "+createStr+".");

out.println("</BODY>"); out.println("</HTML>"); out.close(); }}

Page 20: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

HTTP 1.0 Tokens

• Tokens don’t contain special characters reserved by RFC2068

• Alphanumeric OK

• URLEncoder: Converts string to MIME format x-www-form-urlencoded

• Converts spaces to “+”• Other characters to 3 character hex number

“%xy”

Page 21: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

Applets and Servlets

• Applet programming problem not servlet

• Let applet use http to communicate to servlet

• servlet can communicate with applet in text, binary, or html

Page 22: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

import java.io.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;

import Eliza.*;

public class ElizaServlet extends HttpServletimplements SingleThreadModel{ ElizaMain eliza; DebugLog logger;

public void init(ServletConfig conf) throws ServletException { super.init(conf);

String logFile,logServer,scriptFile; int res;

logFile = getInitParameter("logfile"); logServer = getInitParameter("logserver"); scriptFile = getInitParameter("scriptfile");

eliza = new ElizaMain();

if((logFile != null)||(logServer != null)) { logger = DebugLog.getSharedLog();

synchronized(logger) { if(!logger.initialized()) { if(logServer != null) { logger.logTo(logServer); } else { logger.logTo(new File(logFile)); } } } }

try { res = eliza.readScript(scriptFile); eliza.setLog(logger); } catch(Exception exp) { res = -1; logger.log(exp); }

Page 23: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

if(res != 0) logger.log("Couldn't create eliza main."); }

/* * REPLACES THE ServletRequest getParameter METHOD * DEPRECATED IN JSDK2.0. */ public String getParameter(ServletRequest request,String name) { String values[]=null; String retVal = null;

if(request != null) values = request.getParameterValues(name);

if((values != null)&&(values.length>0)) { retVal = values[0]; }

return retVal; }

public void doGet(HttpServletRequest request, HttpServletResponse response) {

String message;

message = getParameter(request,"message"); respondToMessage(message,response); }

public void doPost(HttpServletRequest request, HttpServletResponse response) {

String message;

message = getParameter(request,"message");

respondToMessage(message,response); }

Page 24: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

protected void respondToMessage(String message ,HttpServletResponse response){

PrintWriter out=null; String reply;

try { if(message==null) { reply = "Please enter a message to Eliza."; } else if(eliza != null) { reply = eliza.processInput(message); } else { reply = "Sorry, Eliza is not available."; } } catch(Exception exp) { reply = "I am having trouble hearing, " +"please repeat."; logger.log(exp); }

try { response.setContentType("text/plain");

out = response.getWriter();

out.println(reply); } catch(Exception exp) { } finally {

if(out != null) out.close();}

}

public void destroy() { logger.closeLog(); }}

Page 25: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

import java.awt.*;import java.applet.*;import java.net.*;import java.io.*;

public class ElizaApplet extends Applet{ Label response; TextField request; String server;

public void init(){ Font f = new Font("Times-Roman",Font.PLAIN,16); Label message;

response = new Label("Eliza will see you know."); response.setFont(f);

request = new TextField(24); request.setFont(f);

setLayout(new GridLayout(2,1,5,5));

add(response); add(request);

try { server = getParameter("server"); } catch(Exception exp) { server = null; }}

Page 26: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

public boolean action(Event evt, Object what) { if(evt.target == request) { String reply; String message; DataInputStream reader; InputStream in=null; URL url;

try { message = "message="; message += URLEncoder.encode(request.getText());

if("POST".equals(getParameter("method"))) { URLConnection connection; PrintStream printOut; url = new URL(server); connection = url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); //Work around for netscape settings for //post requests connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

printOut=new

PrintStream(connection.getOutputStream()); printOut.print("message="+URLEncoder.encode(message)); printOut.flush(); printOut.close(); in = connection.getInputStream(); }

Page 27: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

else { url = new URL(server+"?message="+URLEncoder.encode(message));

in = url.openStream(); }

reader = new DataInputStream(in);

reply = reader.readLine();

reader.close(); in.close(); } catch(Exception exp) { //reply = "Error, network may be down."; reply = exp.toString(); }

response.setText(reply); request.selectAll(); }

return true; }}

Page 28: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

## Servlets Properties#servlet.eliza.code=ElizaServletservlet.eliza.initArgs=scriptfile=c:\\temp\\script

servlet.logservlet.code=LoggingSerlvetservlet.logservlet.initArgs=logserver=192.168.0.172

servlet.adrotator.code=AdRotatorServletservlet.adrotator.initArgs=imagedir=c:\\temp\\ads

servlet.cookiecounter.code=CookieCounterServlet

servlet.lockingservlet.code=FileLockingServlet

servlet.lifecycle.code=LifeCycleServlet

servlet.printenvservlet.code=PrintEnvServlet

servlet.sessioninfo.code=SessionInfoServlet

servlet.hello.code=HelloWorldServlet

Page 29: Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their

<HTML><HEAD><TITLE>Eliza</TITLE></HEAD><BODY><APPLET NAME="Eliza" CODE="ElizaApplet" WIDTH=400 HEIGHT=60><PARAM NAME="server" VALUE="http://192.168.0.172:8080/servlet/eliza"><PARAM NAME="method"VALUE="GET"></APPLET></BODY></HTML>