Compute "); op1 = (int)(Math.random()*100)+1; op2 = (int)(Math.random()*100)+1; out.println("
"); out.println("

"+op1+" + "+op2+" = "); out.println(""); out.println(""); out.close(); }"> Compute

"); op1 = (int)(Math.random()*100)+1; op2 = (int)(Math.random()*100)+1; out.println(""); out.println("

"+op1+" + "+op2+" = "); out.println(""); out.println(""); out.close(); }">

Presentation is loading. Please wait.

Presentation is loading. Please wait.

Session Tracking Honjo-Waseda 2008.

Similar presentations


Presentation on theme: "Session Tracking Honjo-Waseda 2008."— Presentation transcript:

1 Session Tracking Honjo-Waseda 2008

2 Lets try this servlet (Get)
public class Compute extends HttpServlet { int op1, op2; protected void doGet(request, response) throws Exception { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<h1> Compute </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=result>"); out.println("<input type=submit value=check>"); out.close(); }

3 Lets try this servlet (Post)
protected void doPost( request, response) throws Exception { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String res = request.getParameter("result"); int nres = Integer.parseInt(res); out.println("<h2>"); if (nres == op1+op2) out.println("Excelent !"); else out.println(" The result was "+(op1+op2)); }

4 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

5 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

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

7 The same servlet WITH sessions
public 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(); }

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

9 ¿ How to add products with every visit to the order page ?
Normally, the user will go through different pages adding products to the “shopping chart” We can use a session object to store this in pares <product code><added quantity> After each visit the elements of the session object are updated according to what was added

10 Lets see again the product selection
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.code); out.print("<TD>" + e.desc ); 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'>");

11 Now “memorize” the selection
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 qttyOld = (String)s.getAttribute(number); if (qttyOld == null) s.setAttribute(code,qtty+""); else { int qttyNew = Integer.parseInt(qttyOld)+nqtty; s.setAttribute(code,qttyNew+""); } Product e = (Product)item.get(number); out.print("<TR> <TD>" + e.code+"<TD>" + e.desc ); out.print("<TD>" + e.price+"<TD>“+e.price*nqtty); out.println("</TABLE>");

12 Show what we have so far out.println("<TR> <TD> FINAL TOTAL<TD> <TD> <TD>"+total); out.println("</TABLE>"); out.println("<INPUT TYPE='SUBMIT' VALUE='Process'>"); out.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"); total = 0; Enumeration e = s.getAttributeNames(); while(e.hasMoreElements()) { String number =(String)e.nextElement(); out.print("<TR><TD>" + number + "<TD>"); String scantidad =(String)s.getAttribute(number); int ncantidad = Integer.parseInt(scantidad); out.println(ncantidad); Product p = (Product)h.get(number); out.println("<TD>"+(ncantidad*p.price)); total = total + ncantidad*p.price; } out.println("</TABLE><br>"); out.println("<a href='OrderPage'> return to order </a> <br>"); out.println("<a href='CuentaPage'> make order </a>");

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

14 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();

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

16 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();

17 Cookie Methods int getMaxAge() String getName() String getValue()
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.

18 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

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

20 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

21 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

22 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

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

24 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

25 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


Download ppt "Session Tracking Honjo-Waseda 2008."

Similar presentations


Ads by Google