This article explains in detail:
1. Demonstrate the basic usage of cookies
2. Demonstrate the access permissions of cookies
3. Demonstrate Cookie Deletion
4. Use cookies to display the last time the user logged in
5. Use cookie technology to display several pictures recently browsed by users
6. Test how many cookies and how big is the maximum Cookie of Firefox browser?
1. Demonstrate the basic usage of cookies
index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> </head> <body> <h1> Demonstrate Cookie Technology</h1> <a href="CookieDemo">Demonstrate Basic Usage of Cookie</a><br/> </body></html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" 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 cookies to the client Random r = new Random(); int n =r.nextInt(100); String name = "jack";//The format of cookie: key=value Cookie c = new Cookie("name", name+n); c.setMaxAge(60*60);//Set the expiration time, in seconds c.setPath( request.getContextPath() );//This path is: /Project name//In the Cookie mechanism, permissions are controlled through path. Only servlets with the same path as the path or subpath can access the cookie //If the path of a cookie is set as the project root directory, then all servlets under the project can access it response.addCookie(c); //This demonstration cookie has Chinese String str = "I bring Chinese"; str = URLEncoder.encode(str, "utf-8");//Set encoding in Chinese! ! ! urlencode encoding cookie cStr = new cookie("str", str); //If setMaxAge is not set, the browser expires as soon as it is closed cStr.setPath("/"); response.addCookie(cStr); //Read cookie cs[] = request.getCookies();//Read cookie if(cs!=null){//Beware of for(Cookie cc:cs){ String name2 = cc.getName(); String val = cc.getValue(); val = URLDecoder.decode(val, "utf-8");//It turns out that it will decode it as it is encoded! Chinese decoding, ascii is as it is! out.print(name2+"="+val+"<br/>"); } } out.print("Cook saved successfully!"); }}Demonstration results:
On the first click! Session will be discussed next time! Tomcat is automatically generated and sent to the client!
When entering again!
name+n Because the n behind is being generated randomly, this click always displays the information of the previous one!
2. Demonstrate the access permissions of cookies
index.jsp:
<a href="servlet/CookieDemo2">Demonstrate the access permissions of cookies</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 response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); //Write cookies 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, permissions are controlled through path // Since the url-pattern of CookieDemo is the project root directory/CookieDemo, and is not a subdirectory of the path set by the current cookie, the cookie cannot be accessed //Note! ! ! If the path is different, then the cookie is a different object, which means that the cookie with the same name will not be overlapped! response.addCookie(c); //Read cookies sent from the client Cookie 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("Cookie is saved successfully!"); }}Demonstration results:
First enter the CookieDemo2 page to access the CookieDemo name-cookie
Enter the CookieDemo page again, and cannot access the CookieDemo2 age-cookie
3. Demonstrate Cookie Deletion
index.jsp:
<a href="servlet/DelCookieDemo"> Demonstrate the deletion of cookies</a><br/>
web.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.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class DelCookieDemo extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) 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 set by the cookie or the sub-path of the path set by it //Delete the name cookie if("name".equals(c.getName())){ c.setPath( request.getContextPath() );//When deleting, the permission is judged through this sentence! This must be exactly the same as the original path set to delete, otherwise it cannot be deleted! //For the previous sentence, my personal understanding is: because if your path settings are different, it is actually just like a new cookie is opened. The expiration time of the new cookie is 0, and the name is "name" c.setMaxAge(0);// When expiration, see set to 0, which means deletion---The deletion logo is just set here to respond.addCookie(c); } } } } }}Demonstration results:
At this time, name still exists.
We visit DelCookieDemo.
Go to the first link to read:
The name is gone!
Firefox will automatically delete expired cookies:
4. Use cookies to display the last time the user logged in
index.jsp:
<a href="LoginServlet">Use cookies to display the last time the user logged in</a>
web.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 response) 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>Demonstrate using cookies to display the last login time of the user</TITLE></HEAD>"); out.println(" <BODY>"); //Read the client's cookie Cookie cs[] = request.getCookies(); boolean boo = false; if(cs!=null){ for(Cookie c:cs){ //Travel if("loginTime".equals(c.getName())){ String val =c.getValue(); long dt = Long.parseLong(val); Date d = new Date(dt); SimpleDateFormat sdf = new SimpleDateFormat("yyyyy year MM month dd date HH:mm:ss"); out.print("Your last login time was: "+sdf.format(d)); boo=true; break; } } } if(boo==false){// means there is no access record in one year before! Because the expiration time we save below is out.print("You are visiting for the first time in the last year..."); } // Whether it is new or old users, a cookie will be created in the last two times and written to the client. What I have originally had 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(); }}Demonstration results:
First visit;
Visit again:
5. Use cookie technology to display several pictures recently browsed by users
index.jsp:
<a href="jsps/show.jsp">Look at beauties-using cookie technology to display several pictures recently browsed by users</a>
web.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"><html> <head> <style type="text/css"> .span{ border:0px solid #000; width:100px; height:100px; overflow:hidden; } .span img{ max-width:100px; _width:expression(this.width > 100 ? "100px" : this.width); } .spans{ border:0px solid #000; width:50px; height:50px; overflow:hidden; } .spans img{ max-width:50px; _width:expression(this.width > 50 ? "50px" : this.width); } </style> </head> <body> <h1>Look at beauties-Use cookie technology to display several pictures recently browsed by users</h1> <a href="/myCookieWeb/jsps/show.jsp">Look at the beauty-using Cookie technology to display several pictures recently browsed by the user</a> <h3>Recently browsed pictures:</h3> <!-- Add pictures of the last 3 views--> <% String str =null; Cookie cs[] = request.getCookies(); if(cs!=null){ for(Cookie c:cs){ if("images".equals(c.getName())){ str=c.getValue();// ***.jpg break; } } } if(str!=null){ String strs[] = str.split(","); for(String s:strs){ %> <span> <img src="<%=request.getContextPath()%>/imgs/<%=s%>" /> </span> <% } } %> <br/><hr/><br/> <% //Use file to traverse all pictures and display them. String path = getServletContext().getRealPath("/imgs"); //System.out.printf(path); //D:/apache-tomcat-7.0.30/webapps/myCookieWeb/jsps File file = new java.io.File(path); File[] files = file.listFiles(); if(files!=null){ %> <% for(File f:files){ String imgName = f.getName(); %> <span> <a href="<%=request.getContextPath() %>/showImg?img=<%=imgName %>"> <img src="<%=request.getContextPath()%>/imgs/<%=imgName%>" /> </a> </span> <% } %> <% } %> </body></html>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 response) 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(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); String img = request.getParameter("img"); String imgStr = "<img src='"+request.getContextPath()+"/imgs/"+img+"'//>"+img+"'//Use cookies to record the image information visited by the user Cookie cs[] = request.getCookies(); boolean boo = false; if(cs!=null){ for(Cookie c:cs){ if("images".equals(c.getName())){//I already have images cookie String imgs = c.getValue(); String imgStrs[] = imgs.split(","); boolean booStr = false; //Precautions to click duplicate images for(int i=0;i<imgStrs.length;i++){ if(imgStrs[i].equals(img)){ if(i==1&&imgStrs.length==2){ imgs=imgStrs[i]+","+imgStrs[0]; }else if(i==2&&imgStrs.length==3){ imgs=imgStrs[i]+","+imgStrs[0]+","+imgStrs[1]; }else if(i==2&&imgStrs.length==3){ imgs=imgStrs[i]+","+imgStrs[0]+","+imgStrs[1]; } booStr=true; break; } } if(!booStr){ imgs = img+","+imgs;//It will be a little troublesome to use the following method: imgs+","+img if(imgs.split(",").length>3){//If the image visited more than 3 times imgs = imgs.substring(0, imgs.lastIndexOf(","));//Include left, not right} /*//If you write this, it is best to reverse the order of adding the above prevent duplicate images.//imgs+","+img Method: imgs = imgs+","+img; if(imgs.split(",").length>3){//If the image visited more than 3 times imgs = imgs.substring(imgs.indexOf(",")+1, imgs.length()); } */ } c.setValue(imgs);//Update c.setMaxAge(60*60*24*30); c.setPath("/");//Equivalent to completely relaxing access rights, that is, all projects can access response.addCookie(c); boo=true; break; } } } if(boo==false){//Indicate the first visit, that is, there is no image browsing in the browser Cookie c = new Cookie("images", img); c.setMaxAge(60*60*24*30); c.setPath("/"); response.addCookie(c); } out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); }}Demonstration results:
6. Test how many cookies and how big is the maximum Cookie of Firefox browser?
index.jsp:
<a href="servlet/HowManyCookieServlet">Test the maximum number of cookies and one cookie that Firefox browser supports</a><br/>
web.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 response) throws ServletException, IOException { PrintWriter out = response.getWriter(); /* //Num of tests--Firefox 47.0.1 supports up to 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 is the largest supported single cookie storage String s =""; for(int i=0;i<4092;i++){ s+="1"; } Cookie c = new Cookie("test", s); c.setMaxAge(60*15); c.setPath("/"); response.addCookie(c); Cookie cs[] = request.getCookies();//Read cookie if(cs!=null){//Beware of for(Cookie cc:cs){ String key = cc.getName(); String val = cc.getValue(); out.print(key+"="+val+" "); } } }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.