Top Banner
Session Tracking
25

Session Tracking

Jan 08, 2016

Download

Documents

annis@

Session Tracking. Why this servlet did not work?. public class CalculaSession extends HttpServlet { int op1, op2; protected void doGet(request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Session Tracking

Session Tracking

Page 2: Session Tracking

Why this servlet did not work?public class CalculaSession extends HttpServlet {

int op1, op2;

protected void doGet(request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<h1> Calcula </h1>"); op1 = (int)(Math.random()*100)+1; op2 = (int)(Math.random()*100)+1; out.println("<form method=post>"); out.println("<h2>"+op1+" + "+op2+" = "); out.println("<input type=text size=4 name=resultado>"); out.println("<input type=submit value=corregir>"); out.close(); }

Page 3: Session Tracking

Why this servlet did not work?

protected void doPost( request, response) throws Exception {

response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String res = request.getParameter("resultado"); int nres = Integer.parseInt(res); out.println("<h2>"); if (nres == op1+op2) out.println("Excelente "); else out.println(" El resultado era "+(op1+op2)); }

}

Page 4: Session Tracking

A servlet is concurrent• Op1 and op 2 are global parameters

• Every time a new user contacts the servlet it generates new values for these variables

• During the time a user visits the doGet procedure and the doPost procedure another user may change the values of op1 and op2

• This will cause that the servlet wil chek the users answer against the last generated values

• The “right” answer will then be considered wrong by the servlet

• In order to avoid this the servlet has to remember which where the numbers generated for a certain user

• This is done with the help of session tracking

Page 5: Session Tracking

Session Tracking • Session tracking is a mechanism that servlets may use to

maintain a state for a client during a session

• A session is a dialogue between an instance of a browser and the server for a certain period of time (default is 30 minutes).

• It is possible to associate information to the session objects, which is kept on the server during the session

• The session is not managed by the programmer but by the server.

• See SessionServlet

Page 6: Session Tracking

Some methods • HttpSession sesion = request.getSession(true) cretes a

session object if it did not existed already• sesion.isNew()returns true if the above methods created a new object• sesion.putAttribute/Value(String nombre, Object

valor) associates to the parameter nombre the value valor (value se usa hasta v2.2)

• Object o = sesion.getAttribute/Value(“nombre”)returns the object associated to that prameter for that session

• sesion.removeAttribute/Value(“nombre”)deletes the object associated to the parameter named “nombre” for that session

• Enumeration[]valores = sesion.getAttributeNames()• String[]valores = sesion.ValueNames() returns an

array/ennumeration of names for attributes/values the session has stored • long l = sesion.getCreationTime()returns the time (in

milliseconds starting from 1.1.70 0:0:0 ) the session object was created• Long l = sesion.lastAccessedTime() returns the time of the

las access • sesion.setMaxInactiveInterval(int seconds)sets the

timeout of the session

Page 7: Session Tracking

The same servlet WITH sessionspublic class CalculaSession extends HttpServlet {

int op1, op2;

protected void doGet(request, response) throws Exception { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(false); out.println("<h1> Calcula </h1>"); op1 = (int)(Math.random()*100)+1; op2 = (int)(Math.random()*100)+1; session.setAttribute("op1",""+op1); session.setAttribute("op2",""+op2); out.println("<form method=post>"); out.println("<h2>"+op1+" + "+op2+" = "); out.println("<input type=text size=4 name=resultado>"); out.println("<input type=submit value=corregir>"); out.close(); }

Page 8: Session Tracking

The same servlet WITH sessions

protected void doPost( request, response) throws Exception { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true); String res = request.getParameter("resultado"); int nres = Integer.parseInt(res); op1 = Integer.parseInt((String)session.getAttribute("op1")); op2 = Integer.parseInt((String)session.getAttribute("op2")); out.println("<h2>"); if (nres == op1+op2) out.println("Excelente "); else out.println(" El resultado era "+(op1+op2)); }}

Page 9: Session Tracking

¿ Como acumular productos en varias visitas ?

• La idea es que en cada visita se vayan seleccionando productos

• Estos se van acumulando para cada usuario• Se puede usar un objeto Session para

guardad pares – <codigo de producto><cantidad acumulada>

• Despues con cada visita se actualiza el estado de estos pares según lo que se seleccionó

Page 10: Session Tracking

Veamos de nuevo la selección de productos

public void doGet( .. request, ... response) throws . . . {

Hashtable items = Item.getItems(); . . . .

. . . . out.print("<form action=ProcessPage method='POST'>"); while(enum.hasMoreElements()) { Product e = (Product)enum.nextElement(); out.print("<TR>"); out.print("<TD>" + e.number); out.print("<TD>" + e.name ); out.print("<TD>" + e.price+"<TD>"); out.print("<input type=textarea SIZE=3 "+ out.print(" name="+e.number+" value=0 >"); } out.println("</TABLE>"); out.println("<INPUT TYPE='SUBMIT' VALUE='Process'>");}

Page 11: Session Tracking

Incorporemos la memorización public void doGet( .. request, ... response) throws . . . { Hashtable items = Item.getItems(); HttpSession s = request.getSession(true); . . . Enumeration en = request.getParameterNames(); int total = 0; out.print("<form action=ProcessPayment method='POST'>"); while(en.hasMoreElements()) { String number = (String)en.nextElement(); String qtty = request.getParameter(number); int nqqty = Integer.parceInt(qtty); if (nqqty == 0) continue; String qttyAntigua = (String)s.getAttribute(number); if (qttyAntigua == null) s.setAttribute(codigo,cantidad+""); else { int qttyNueva = Integer.parseInt(qttyAntigua)+nqtty; s.setAttribute(codigo,nuevaCantidad+""); } Product e = (Product)item.get(number); out.print("<TR> <TD>" + e.number+"<TD>" + e.name ); out.print("<TD>" + e.price+"<TD>“+e.price*nqtty); } out.println("</TABLE>");

Page 12: Session Tracking

Mostremos lo que llevamosout.println("</TABLE>\n</BODY></HTML>"); out.println("<br><br><h2> So far you have chosen</h2>"+ "<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + "<TH>codigo<TH>cantidad<TH> subtotal"); int total = 0; Enumeration e = s.getAttributeNames(); while(e.hasMoreElements()) { String codigo =(String)e.nextElement(); out.print("<TR><TD>" + codigo + "<TD>"); String scantidad =s.getAttribute(codigo); int ncantidad = Integer.parseInt(scantidad); out.println(ncantidad); Product e = (Product)item.get(number); out.println(“<TD>”+(ncantidad*e.price)); total = total + ncantidad*e.price; } out.println("</TABLE><br>"); out.println("<a href='OrderPage'> return to order </a> <br>"); out.println("<a href='CuentaPage'> make order </a>"); }}

Page 13: Session Tracking

Using Cookies • Cookies are another way to keep track of what the client

has been doing • Trough a cookie the servlet can send information to the

client so it can store it and send it every time it contacts the server again.

• The Servlets send cookies to the clients adding information to the header of the Http response it send to the client.

• The clients automatically return these cookies when thy contact the server again for a further request as additional information on the HTTP request.

• Cookies have a name and a value (both strings) Additionally they can store a comment

• A server can pass more than a cookie to the client.

Page 14: Session Tracking

Using Cookies • To send a cookie 1. Instantiate a Cookie object

Cookie c = new Cokie(string, string);

2. Send cookie

response.addCookie(c);

• To retrieve the information of a cookie, 1. Retrieve all cookies from the client

Cookie[] c = request.getCookies();

2. Retrieve name and value

String name = c[i].getName();

String value = c[i].getValue();

Page 15: Session Tracking

Example Cookies void doGet(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<h1> Agregue una cookie </h1> <h2>"); out.println("<form method=POST>"); out.println("Nombre : <input type=text name=cnombre>"); out.println("Valor : <input type=text name=cvalor>"); out.println("<br> <input type=submit value=enviar>"); out.println("</html>"); out.close(); }}

Page 16: Session Tracking

protected void doPost( … response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); Cookie[] c = request.getCookies(); String cn = request.getParameter("cnombre"); String cv = request.getParameter("cvalor"); if (cn != null && cv != null) { Cookie nuevacookie = new Cookie(cn,cv); response.addCookie(nuevacookie); out.println("<h1>La cookie con nombre "+cn+ " y valor "+cv+" sera mandada</h1>"); } if (c != null) { out.println("<h2> ademas las siguientes cookies fueron recibidas </h2>"); for (int i = 0; i < c.length; i++) out.println("<br>Nombre : "+c[i].getName()+" valor : "+c[i].getValue()); } out.print("<form><input type=submit value=retornar>"); out.close(); }

Page 17: Session Tracking

Cookie Methods • int getMaxAge()  

– Returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown. 

• String getName() – Returns the name of the cookie. 

• String getValue()– Returns the value of the cookie. 

• void setComment(String comment)– Specifies a comment that describes a cookie's purpose. 

• voidsetMaxAge(int expiry)– Sets the maximum age of the cookie in seconds. 

• void setValue(String newValue)– Assigns a new value to a cookie after the cookie is created.

Page 18: Session Tracking

Examples of Cookies• The first example (Cookies.java) shows the times

when the client contacted the servlet for the first time (via doGet method) and the time when it contacted the server by pressing the button

• The second example (CookieExample) shows how to retrieve all the cookies

• The third example ( SetCookie and ShowCookies) shows how to put time-out values for a cookie

Page 19: Session Tracking

¿ Cookies or Sessions ? • With sessions the information is stored on the server,

this means, there is a state which has to be administrated carefully

• With cookies it is the client which has the information, this means the information travels back and forth every time the client contacts the server

• The client can prohibit the use of cookies• Sessions can store much more (and better)

information• Sessions are implemented with cookies !!!!!!!!

Page 20: Session Tracking

The headers of request and response• Provide high level information from the client and to the

client – The request allows the servlet to obtain interesting characteristics of

the client– The response allows the servlet to define how the information will be

delivered to the browser

• In general, they help make the dialog with the client more effective

• For the request, there are methods called getXXX or getHeader(xxx) to obtain information

• For the response, there are methods called setHeader(xxx) or setXXX for defining the form of the response data.

• Often both are required to be used in combination to generate an adequate response

Page 21: Session Tracking

Some get for the request• getCookies(): received the cookies which the client browser

may have sent• getAuthType(): is used for clients trying to access a page for

which a password is required • getRemoteHost(): to obtain the hostname of the client• getMethod(): to get the name of the method with which the

browser contacted the servlet (GET, POST, etc..)• getProtocol(): version of the HTTP protocol the client is

using• getHeaderNames(): the name of all the headers the client has

sent (is variable depending on the HTTP and browser version

Page 22: Session Tracking

Some xxx for the getHeader(xxx)• “Accept”: which MIME types the client “understands” • “Accept-Charset”: which character set the client is using • “Accept-Encoding”: encoding algorithms the client accepts• “Accept-Language”: language (en-us, sp, ge, ..)• “Authorization”: to identify clients with a protected page• “Host”: the client’s computer name• “Referer”: the URL of the page that generated the contact • “Cookie”: to obtain the cookies

Page 23: Session Tracking

Some set for the response• setContentType(xxx): for informing the MIME type of the

response

• setContentLength(xxx): for informing the length of the response (used when transmitting bytes)

• addCookie(c): to add cookies with information to the client

• sendRedirect(xxx): to redirect the request to another URL

• setHeader(xxx,xxx) a general form

• setIntHeader(xxx,xxx) when the second argument is an integer (no need to convert to string)

Page 24: Session Tracking

Some xxx for the setHeader(xxx,xxx)

• Content-Type: some MIME type like “image/gif”• Content-Length: length (para bytes)• Content-Encoding: codification• Content-Language: language• Cache: como se debe manejar el cache en el cliente (ej, no-

cache, no-store, must-revalidate, max-age=xxxx, • Refresh: informs the browser how often the page should be

refreshed• www-Authenticate: for managing pages protected with

passwords

Page 25: Session Tracking

Some more elaborated exemples showing the use of these methods• ShowRequestHeaders: just shows the

headers of the request

• ProtectedPage: shows how to ask for a password (run PasswordBuilder first)

• Ping & Pong: shows redirection