Learn more about Java Cookie Technology (user login, browsing, access rights) _java

Source: Internet
Author: User
Tags flush

This article explains in detail:
1, the basic use of Cookies demo
2. Demo Cookie access rights
3. Demo Cookie Deletion
4, using cookies to display the user's last login time
5, using the cookie technology to display the user recently browsed several pictures
6, test Firefox browser in the end how many cookies and a cookie max for how big

1, the basic use of Cookies demo

INDEX.JSP:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <!

DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
 
 

Xml:

<?xml version= "1.0" encoding= "UTF-8"?> <web-app version=
"3.0" xmlns= "http://java.sun.com/xml/ns/" 
 Java ee " 
 xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance " 
 xsi:schemalocation=" http://java.sun.com/ Xml/ns/javaee 
 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd ">
 <display-name></ display-name>
 <servlet>
 <servlet-name>CookieDemo</servlet-name>
 < servlet-class>cn.hncu.servlets.cookiedemo</servlet-class>
 </servlet>

 < servlet-mapping>
 <servlet-name>CookieDemo</servlet-name>
 <url-pattern>/ cookiedemo</url-pattern>
 </servlet-mapping> 
 <welcome-file-list>
 < welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

Cookiedemo.java:

Package cn.hncu.servlets;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Java.net.URLDecoder;
Import Java.net.URLEncoder;

Import Java.util.Random;
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 Cookiedemo extends HttpServlet {public void doget (HttpServletRequest request, httpservletresponse response
 ) throws Servletexception, IOException {response.setcontenttype ("text/html;charset=utf-8");

 PrintWriter out = Response.getwriter ();
 Write a cookie to the client Random R = new Random ();
 int n =r.nextint (100);
 String name = "Jack";//cookie format: key=value cookie c = new Cookie ("name", Name+n); C.setmaxage (60*60)//Set the expiration time, in seconds C.setpath (Request.getcontextpath ());//The path is:/project name//cookie mechanism in which permissions are controlled through path. Only a servlet with <url-pattern> and the same path or its subpath can access the cookie//If you set the path of a cookie to the project root, then all the servlet under the project will be able to visitAsk It Response.addcookie (c);
 This demo cookie takes Chinese String str = "I bring Chinese"; str = Urlencoder.encode (str, "utf-8");//Chinese SET encoding!!!
 UrlEncode encoded Cookie CSTR = new Cookie ("str", str);
 If Setmaxage is not set, the browser expires Cstr.setpath ("/") as soon as it closes;

 Response.addcookie (CSTR); Read Cookie cookie cs[] = request.getcookies ()//Read Cookie if (cs!=null) {//guard against for (Cookie Cc:cs) {String name2
  = Cc.getname ();
  String val = Cc.getvalue (); val = Urldecoder.decode (val, "Utf-8");/the original is how to encode, how to decode!
  Chinese decoding, ASCII is the same!
  Out.print (name2+ "=" +val+ "<br/>"); } out.print ("Cook save success!")
 ");

 }

}

Demo results:

The first time you clicked! Session Next time Speak! Tomcat is automatically generated to the client!

Enter again!
name+n– because the back of the n has been randomly generated, this click always shows the previous information!

2. Demo Cookie access rights

INDEX.JSP:

<a href= "Servlet/cookiedemo2" > Demo cookie access rights </a><br/>

Web.xml:

<servlet>
 <servlet-name>CookieDemo2</servlet-name>
 <servlet-class>cn.hncu.servlets.CookieDemo2< /servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>cookiedemo2</ servlet-name>
 <url-pattern>/servlet/CookieDemo2</url-pattern>
 </servlet-mapping> 

Cookiedemo2.java:

Package cn.hncu.servlets;
Import java.io.IOException;
Import Java.io.PrintWriter;

Import Java.util.Random;
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 CookieDemo2 extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Respon
 SE) throws Servletexception, IOException {response.setcontenttype ("text/html;charset=utf-8");

 PrintWriter out = Response.getwriter ();
 Write a cookie to the client Random R = new Random ();
 int n =r.nextint (100);
 Cookie C = New Cookie ("Age", "" +n); C.setmaxage (60*60);//Expiration Time C.setpath (Request.getcontextpath () + "/servlet/cookiedemo2"); in the//cookie mechanism, the permissions are controlled by path. /Because the Url-pattern of Cookiedemo is the project root/cookiedemo, not a subdirectory of the path set by the current cookie, the cookie//note cannot be accessed!!!
 Path is not the same, then the cookie is a different object, that is, does not repeat the same name cookie!

 Response.addcookie (c); Read the cookie cookie from the client cs[] = Request.getcooKies ();
  if (Cs!=null) {for (Cookie Cc:cs) {String name = Cc.getname ();
  String val = Cc.getvalue ();
  Out.print ("22222--" +name+ "=" +val+ "<br/>"); } out.print ("Cookies saved successfully!")

 ");

 }
}

Demo results:

Enter the CookieDemo2 page first to access the Cookiedemo Name-cookie

Enter the Cookiedemo page again, can not access to CookieDemo2 's Age-cookie

3. Demo Cookie Deletion

INDEX.JSP:

<a href= "Servlet/delcookiedemo" > Demo cookie deletion </a><br/>

Xml:

<servlet>
 <servlet-name>DelCookieDemo</servlet-name>
 <servlet-class> cn.hncu.servlets.delcookiedemo</servlet-class>
 </servlet>
 <servlet-mapping>
 < Servlet-name>delcookiedemo</servlet-name>
 <url-pattern>/servlet/delcookiedemo</ Url-pattern>
 </servlet-mapping>

Delcookiedemo.java:

Package cn.hncu.servlets;
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; public class Delcookiedemo extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Respo
 NSE) throws Servletexception, IOException {response.setcontenttype ("text/html;charset=utf-8");
 PrintWriter out = Response.getwriter ();
 Cookie cs[] = request.getcookies (); if (Cs!=null) {for (cookie C:cs) {//to traverse to the "name" Cookie, the current servlet must have Read permission. That is, the url-pattern of the servlet must be the path to which the cookie is set or the subpath//delete name of the path to which it is set ("Name". Equals (C.getname ())} {C.setpath (Request Getcontextpath ());//delete is to judge the right by this sentence!
   This must be the same as the original set of the path to delete, or you can not delete! For the last sentence, my personal understanding is: Because if you set this path differently, it's just quite a new cookie, the expiration time for this new cookie is 0,name is "name" C.setmaxage (0); That is, delete---here just set the delete identity Response.addcoOkie (c);
 }
  }
 }
 }
}

Demo results:

At this time, name still exists.

We visit Delcookiedemo.

Then go to the first link to see:

Name is gone!

Firefox will automatically delete expired cookies:

4, using cookies to display the user's last login time

INDEX.JSP:

<a href= "Loginservlet" > Use cookies to display the time the user last logged in </a>

Xml:

 <servlet>
 <servlet-name>LoginServlet</servlet-name>
 <servlet-class> cn.hncu.servlets.loginservlet</servlet-class>
 </servlet>
 <servlet-mapping>
 < Servlet-name>loginservlet</servlet-name>
 <url-pattern>/LoginServlet</url-pattern>
 </servlet-mapping>

Loginservlet.java:

Package cn.hncu.servlets;
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 Loginservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Respo
 NSE) throws Servletexception, IOException {response.setcontenttype ("text/html;charset=utf-8");
 PrintWriter out = Response.getwriter (); Out.println ("<!
 DOCTYPE HTML public \-//w3c//dtd HTML 4.01 transitional//en\ ">");
 Out.println ("<HTML>");
 Out.println ("<HEAD><TITLE> demo uses cookies to show user last login Time </TITLE></HEAD>");

 Out.println ("<BODY>");
 Read the client's cookie cookie cs[] = request.getcookies ();
 Boolean boo = false; if (Cs!=null) {for (Cookie C:cs) {//Traverse if ("Logintime". Equals (c.geTname ()) {String Val =c.getvalue ();
   Long dt = Long.parselong (val);
   Date d = new date (DT);
   SimpleDateFormat SDF = new SimpleDateFormat ("yyyy mm month DD Day HH:mm:ss");
   Out.print ("Your last logon time is:" +sdf.format (d));
   Boo=true;
  Break }} if (Boo==false) {//indicates no access record for the previous 1 years! Because the expiration time we save below is one year out.print ("Your last year is your first visit ...").
 "); }//Both new and old users will create a cookie with the most recent time to write to the client.
 The original has, is the update time Date d = new Date ();
 Cookie C = new Cookie ("Logintime", "" "+d.gettime ());
 C.setpath (Request.getcontextpath ());
 C.setmaxage (60*60*24*30*12);

 Response.addcookie (c);
 Out.println ("</BODY>");
 Out.println ("</HTML>");
 Out.flush ();
 Out.close ();

 }

}

Demo results:

First visit;

Visit again:

5, using the cookie technology to display the user recently browsed several pictures

INDEX.JSP:

<a href= "jsps/show.jsp" > See Beauty--using cookie technology to display a number of recent images viewed by users </a>

Xml:

 <servlet>
 <servlet-name>ShowServlet</servlet-name>
 <servlet-class> cn.hncu.servlets.showservlet</servlet-class>
 </servlet>
<servlet-mapping>
 < servlet-name>showservlet</servlet-name>
 <url-pattern>/showImg</url-pattern>
 </ Servlet-mapping>

SHOW.JSP:

<% @page import= "java.io.File"%> <%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> < ! 
 DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  
 

Showservlet.java:

Package cn.hncu.servlets;
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; public class Showservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Respon
 SE) throws Servletexception, IOException {response.setcontenttype ("text/html");
 PrintWriter out = Response.getwriter (); Out.println ("<!
 DOCTYPE HTML public \-//w3c//dtd HTML 4.01 transitional//en\ ">");
 Out.println ("<HTML>");
 Out.println (" 
 

Demo results:

6, test Firefox browser in the end how many cookies and a cookie max for how big

INDEX.JSP:

<a href= "Servlet/howmanycookieservlet" > Test how many cookies and a cookie Max are supported by Firefox browser </a><br/>

Xml:

 <servlet>
 <servlet-name>HowManyCookie</servlet-name>
 <servlet-class> cn.hncu.servlets.howmanycookie</servlet-class>
 </servlet>
 <servlet-mapping>
 < Servlet-name>howmanycookie</servlet-name>
 <url-pattern>/servlet/howmanycookieservlet</ Url-pattern>
 </servlet-mapping>

Howmanycookie.java:

Package cn.hncu.servlets;
Import java.io.IOException;
Import Java.io.PrintWriter;

Import Java.net.URLDecoder;
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 Howmanycookie extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse resp

 Onse) throws Servletexception, IOException {printwriter out = Response.getwriter ();
  *///test number-Firefox 47.0.1 maximum support 110 for (int i=1;i<=110;i++) {Cookie c = new Cookie ("Textnum" +i, "" +i);
  C.setmaxage (60*15);
  C.setpath ("/");
 Response.addcookie (c);
 * *///Test size---4092 bytes for maximum supported single Cookie storage String s = "";
 for (int i=0;i<4092;i++) {s+= "1";
 The cookie c = new Cookie ("test", s);
 C.setmaxage (60*15);
 C.setpath ("/");

 Response.addcookie (c); Cookie cs[] = request.getcookies ()//Read Cookie if (cs!=null) {//guard against for (Cookie Cc:cs) {String key =Cc.getname ();
  String val = Cc.getvalue ();
  Out.print (key+ "=" +val+ ");

 }
 }

 }

}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.