Javaweb Session Management: (1) cookies

Source: Internet
Author: User
Tags send cookies set cookie

Session Technology
Serial Number name Data Storage location
1 Cookie Technology Session data is saved in the browser client.
2 Session Technology Session data is saved on the server side.

1. Cookie Technology



1.1. Features


Cookie Technology: Session data is saved in the browser client.


1.2. The core of Cookie technology


Cookie class: Used to store session data.


Cookie Core API
Serial Number category API
1 Constructing Cookie Objects

Cookie (string name, String value)

2 Set cookies

void SetPath (String uri): Sets the valid access path for the cookie

void setmaxage (int expiry): Set the effective time of the cookie

void SetValue (String newvalue): Sets the value of the cookie

3 Send cookies to browser-side save

void Response.addcookie (Cookie cookie): Sending a cookie

4 Server receives cookies

Cookie[] Request.getcookies (): Receive cookies



1.3. Cookie principle


1) The server creates a cookie object that stores session data in a cookie object.

Cookie cookie = new Cookie ("username", "Lsieun");

2) The server sends cookie information to the browser

Response.addcookie (cookie);

Example: Set-cookie:username=lsieun (hides the response header that sent a set-cookie name)

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/80/E9/wKiom1dET13SkYAjAAAhwbM8yHY063.png "title=" Response_header_set_cookie.png "alt=" Wkiom1det13skyajaaahwbm8yhy063.png "/>

3) The browser gets the cookie sent by the server and then saves it on the browser side.

4) The browser will take cookie information the next time it accesses the server

Example: Cookie:username=lsieun (hide with a request header called Cookie name)

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/80/E8/wKioL1dEUGnwsVLFAABo6ekUy70072.png "title=" Request_header_cookie.png "alt=" Wkiol1deugnwsvlfaabo6ekuy70072.png "/>

5) The server receives the cookie information that the browser brings

cookie[] cookies = request.getcookies ();//Receive cookies sent by the browser if (cookie = null) {for (cookie c:cookies) {String cookiename = C.getname (); String cookievalue = C.getvalue (), int cookieage = C.getmaxage (); Out.write (CookieName + ":" + Cookievalue + ", Age:" + C ookieage);}}

Complete code: Demo01.java

Package Com.rk.http.a_cookie;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.http.cookie;import Javax.servlet.http.httpservlet;import javax.servlet.http.HttpServletRequest; Import javax.servlet.http.httpservletresponse;/** * Send cookies to Browser * @author Lsieun * */public class Demo01 extends Httpserv let{@Overrideprotected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexception{cookie cookie = new Cookie ("username", "Lsieun");//Create Cookie Object Response.addcookie (cookie);// Send cookie data to browser System.out.println ("Cookie Saved!!!");}}

Complete code: Receivecookie.java

package com.rk.http.a_cookie;import java.io.ioexception;import java.io.printwriter;import  javax.servlet.servletexception;import javax.servlet.http.cookie;import  javax.servlet.http.httpservlet;import javax.servlet.http.httpservletrequest;import  javax.servlet.http.httpservletresponse;/** *  receive cookie *  @author from the browser  lsieun *  */public class receivecookie extends httpservlet{@Overrideprotected  void  Doget (Httpservletrequest request, httpservletresponse response)  throws  Servletexception, ioexception{response.setcharacterencoding ("Utf-8"); Response.setcontenttype ("text/html; Charset=utf-8 "); Printwriter out = response.getwriter (); Cookie[] cookies = request.getcookies ();//Receive cookie information sent by browser if (cookies != null)// Note: Determine if null,  otherwise null pointer {out.write ("

package com.rk.http.a_cookie;import java.io.ioexception;import java.io.printwriter;import  javax.servlet.servletexception;import javax.servlet.http.httpservlet;import  Javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;public class  HeaderCookie extends HttpServlet{private int count = 0; @Overrideprotected  void doget (Httpservletrequest request, httpservletresponse response)  throws  servletexception, ioexception{response.setcharacterencoding ("Utf-8"); Response.setcontenttype ("text/ Html;charset=utf-8 "); Printwriter out = response.getwriter ();//1. Use GetHeader () to obtain browser cookie information String strcookie  = request.getheader ("cookie"); Out.write ("Cookie information obtained from the browser is:"  + strCookie +  "< Br/> ");int num = 0;synchronized  (Headercookie.class) {count++;num = count;} 2. Use SetHeader () to set cookie information REsponse.setheader ("Set-cookie",  "username" +num+ "=lsieun" +num);}} 




1.4. Details of cookies

1) void SetPath (java.lang.String uri): Sets the valid access path for the cookie.

Valid path refers to where the valid path of a cookie is saved, and the browser takes cookie information when it accesses the server under a valid path, otherwise it does not have cookie information.

2) void Setmaxage (int expiry): Sets the effective time of the cookie.

Positive integer: Indicates that the cookie data is saved in the browser's cache directory (on the hard disk) and the value indicates the time of the save.

Negative integer: Indicates that the cookie data is saved in the browser's memory. Browser Close cookie is lost!!

0: Delete cookie data with the same name

3) The cookie data type can only be stored in non-Chinese string types.

Multiple cookies can be saved, but browsers generally allow only 300 cookies, with a maximum of 20 cookies per site and a limit of 4KB per cookie size.


Sample Code Demo02.java

package com.rk.http.a_cookie;import java.io.ioexception;import javax.servlet.servletexception; import javax.servlet.http.cookie;import javax.servlet.http.httpservlet;import  Javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;public class  demo02 extends httpservlet{@Overrideprotected  void doget (httpservletrequest  Request, httpservletresponse response)  throws ServletException, IOException{/**  * 1. Creating a Cookie Object  */cookie cookie1 = new cookie ("username", "Lsieun"); Cookie cookie2 = new cookie ("Password", "123456"); Cookie cookie3 = new cookie ("Email", "[email protected]"); Cookie cookie4 = new cookie ("Hobby", "swiming");/** * 2. Set a valid path for the Cookie. Default: The valid path is under the current Web application.  */cookie1.setpath ("/");//valid path is the root directory of the site Cookie2.setpath (Request.getcontextpath ());//And the following three effects are the same COOKIE3.SETPATh ("/myweb");//cookie4 uses the default value/** * 3. Sets the effective time  *  positive integer of the cookie: indicates that the cookie data is saved in the browser's cache directory (on the hard disk), and the value indicates the time of the save.  *  Negative integer: Indicates that the cookie data is saved in the browser's memory. Browser Close cookie is lost!!  *  0: Delete cookie data with the same name  */cookie1.setmaxage (20);//20 seconds, starting from the last non-invocation of the cookie Cookie2.setmaxage (-1); The cookie is saved in the browser memory (session cookie) cookie3.setmaxage (0);//delete cookie data with the same name//COOKIE4 use the default value/** * 4. Sending cookie data to the browser  */response.addcookie (COOKIE1); Response.addcookie (cookie2); Response.addcookie (COOKIE3); Response.addcookie (COOKIE4);}}



1.5. Case-Shows the last time the user visited
package com.rk.http.a_cookie;import java.io.ioexception;import java.io.printwriter;import  java.text.simpledateformat;import java.util.date;import javax.servlet.servletexception;import  javax.servlet.http.cookie;import javax.servlet.http.httpservlet;import  Javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;public class  historycookie extends httpservlet{@Overrideprotected  void doget (httpservletrequest  request, httpservletresponse response)  throws servletexception, ioexception{ Response.setcharacterencoding ("Utf-8"); Response.setcontenttype ("Text/html;charset=utf-8"); Printwriter out = response.getwriter ();/** *  get current time  */SimpleDateFormat  Format = new simpledateformat ("Yyyy-mm-dd hh:mm:ss"); String curtime = format.format (New date ()); Cookie[] cookies = request.getcoOkies (); String lastlogontime = null;if (Cookies != null) {for (cookie c : cookies {if (C.getname () equals ("Lasttime")) {Lastlogontime = c.getvalue ();//1. Display the last access time to the browser out.write ("Welcome back, The last time you visited was: " + lastLogonTime + ", the current time is: " + curtime);//2. Update Cookiec.setvalue ( Curtime); C.setmaxage (1*30*24*60*60);//3. Send the updated cookie to the browser Response.addcookie (c); return;//there is no break. This is because after the break, it jumps out of the current loop, executes the subsequent code, and return exits the current method directly. }}}//first visit (no cookie  or   cookies, but no cookie named Lasttime) if (cookies == null | |  lastlogontime==null) {//1. Displays the current time to the browser out.write ("You are the first to visit this site, the current time is:"  + curTime +  "<br/ >//2. Create a Cookie Object Cookie cookie = new cookie ("Lasttime", Curtime); Cookie.setmaxage (1*30* 24*60*60)//3. Send the cookie to the browser to save the Response.addcookie (cookie);} Else{}}}




Javaweb Session Management: (1) cookies

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.