欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详细学习Java Cookie技术(用户登录、浏览、访问权限)

程序员文章站 2024-03-13 14:07:39
本章文章详细讲解: 1、cookie基本用法演示 2、演示cookie的访问权限 3、演示cookie的删除 4、利用cookie显示用户上次登录的时间...

本章文章详细讲解:
1、cookie基本用法演示
2、演示cookie的访问权限
3、演示cookie的删除
4、利用cookie显示用户上次登录的时间
5、利用cookie技术显示用户最近浏览的若干个图片
6、测试火狐浏览器到底支持多少个cookie和一个cookie最大为多大

1、cookie基本用法演示

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>演示cookie技术</h1>
 <a href="cookiedemo">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();

 //向客户端写cookie
 random r = new random();
 int n =r.nextint(100);
 string name = "jack";//cookie的格式:key=value
 cookie c = new cookie("name", name+n);
 c.setmaxage(60*60);//设置过期时间,以秒为单位
 c.setpath( request.getcontextpath() );//该路径是: /项目名
 //cookie机制中,是通过path来控制权限的。只有<url-pattern>和该path相同或是它的子路径的servlet才能够访问该cookie
 //如果把一个cookie的path设为项目根目录,那么该项目下的所有servlet都能够访问它
 response.addcookie(c);

 //这一段演示cookie带中文
 string str = "我带中文";
 str = urlencoder.encode(str, "utf-8");//中文设置编码!!!urlencode编码
 cookie cstr = new cookie("str", str);
 //如果不设置setmaxage,则浏览器一关闭就过期
 cstr.setpath("/");
 response.addcookie(cstr);

 //读取客户端发过来的cookie
 cookie cs[] = request.getcookies();//读取cookie
 if(cs!=null){//防范一下
  for(cookie cc:cs){
  string name2 = cc.getname();
  string val = cc.getvalue();
  val = urldecoder.decode(val, "utf-8");//原来是怎么编码的,就怎么解码! 中文解码,ascii是原样的!
  out.print(name2+"="+val+"<br/>");
  }
 }

 out.print("cook保存成功!");
 }

}

演示结果:

详细学习Java Cookie技术(用户登录、浏览、访问权限)

第一次点击时!session下次讲!tomcat自动生成发给客户端的!

详细学习Java Cookie技术(用户登录、浏览、访问权限)

再次进入时!
name+n–因为后面的n一直在随机生成,这个点击总是显示的是前一个的信息!

详细学习Java Cookie技术(用户登录、浏览、访问权限)

详细学习Java Cookie技术(用户登录、浏览、访问权限)

2、演示cookie的访问权限

index.jsp:

<a href="servlet/cookiedemo2">演示cookie的访问权限</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();

 //向客户端写cookie
 random r = new random();
 int n =r.nextint(100);
 cookie c = new cookie("age", ""+n);
 c.setmaxage(60*60);//过期时间
 c.setpath( request.getcontextpath()+"/servlet/cookiedemo2" );//cookie机制中,是通过path来控制权限的
 //由于cookiedemo的url-pattern是项目根目录/cookiedemo,不是当前cookie所设路径的子目录,因此无法访问到该cookie

 //注意!!!path不一样,那么cookie是不同的对象,也就是不会覆那个名字相同的cookie!
 response.addcookie(c);

 //读取从客户端发来的cookie
 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保存成功!");

 }
}

演示结果:

先进入cookiedemo2的页面,能访问到cookiedemo的name-cookie

详细学习Java Cookie技术(用户登录、浏览、访问权限)

再进入cookiedemo的页面,不能访问到cookiedemo2的age-cookie

详细学习Java Cookie技术(用户登录、浏览、访问权限)

3、演示cookie的删除

index.jsp:

<a href="servlet/delcookiedemo"> 演示cookie的删除 </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.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){
 //要想遍历到"name"这个cookie,当前servlet必须要有读的权限,即servlet的url-pattern必须是该cookie所设路径或者是其所设路径的子路径
  //删除name这个cookie
  if("name".equals(c.getname())){
   c.setpath( request.getcontextpath() );//删除时是通过这一句来判断权限的!这里必须和原来所设的路径完全一样才能删除,否则不能删除!
   //对于上句,我的个人理解是:因为如果你这个路径设置不同了,其实只是相当与新开了一个cookie,这个新cookie的到期时间是0,name是"name"

   c.setmaxage(0);//到期时见设为0,即是删除---此处只是设置删除标识
   response.addcookie(c);
  }
  }
 }
 }
}

演示结果:

这个时候,name还存在的。

详细学习Java Cookie技术(用户登录、浏览、访问权限)

我们访问delcookiedemo.

详细学习Java Cookie技术(用户登录、浏览、访问权限)

再去第一个链接看:

详细学习Java Cookie技术(用户登录、浏览、访问权限)

name已经没有了!

火狐会自动删除过期的cookie:

详细学习Java Cookie技术(用户登录、浏览、访问权限)

4、利用cookie显示用户上次登录的时间

index.jsp:

<a href="loginservlet">利用cookie显示用户上次登录的时间</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>演示利用cookie显示用户上次登录的时间</title></head>");
 out.println(" <body>");

 //读取客户端的cookie
 cookie cs[] = request.getcookies();
 boolean boo = false;
 if(cs!=null){
  for(cookie c:cs){
  //遍历
  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月dd日 hh:mm:ss");
   out.print("您上次登录时间是:"+sdf.format(d));
   boo=true;
   break;
  }
  }
 }
 if(boo==false){//表示之前1年没有访问记录!因为下面我们保存的过期时间是一年
  out.print("您最近一年是第一次访问。。。");
 }

 //无论是新旧用户,都会以最近的时间俩创建一个cookie,写到客户端。原来有了的,就是更新时间
 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();
 }

}

演示结果:

第一次访问;
详细学习Java Cookie技术(用户登录、浏览、访问权限)

再次访问:

详细学习Java Cookie技术(用户登录、浏览、访问权限)

5、利用cookie技术显示用户最近浏览的若干个图片

index.jsp:

<a href="jsps/show.jsp">看美女--利用cookie技术显示用户最近浏览的若干个图片</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>看美女--利用cookie技术显示用户最近浏览的若干个图片</h1>

 <a href="/mycookieweb/jsps/show.jsp">看美女--利用cookie技术显示用户最近浏览的若干个图片</a>
 <h3>最近浏览的图片:</h3>

 <!-- 添加最近3次浏览的图片 -->
 <%
 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 class="spans">
   <img src="<%=request.getcontextpath()%>/imgs/<%=s%>" />
   </span> 
  <%
  }
 }
 %>

 <br/><hr/><br/>

 <% 
 //利用file遍历所有的图片,显示出来。
 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 class="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+"'/>";
 out.print(imgstr);

 //用cookie记录用户访问过的图片信息
 cookie cs[] = request.getcookies();
 boolean boo = false;
 if(cs!=null){
  for(cookie c:cs){
  if("images".equals(c.getname())){//已经有了images这个cookie
   string imgs = c.getvalue();
   string imgstrs[] = imgs.split(",");
   boolean boostr = false;
   //防范点击重复的图片
   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;//采用如下方式会麻烦一点:imgs+","+img
   if(imgs.split(",").length>3){//如果访问的图片超过3次了
    imgs = imgs.substring(0, imgs.lastindexof(","));//左包含,右不包含
   }

   /*//如果这样写了,最好把上面的防范重复的图片,那个添加顺序倒过来
   //imgs+","+img 方式:
   imgs = imgs+","+img;
   if(imgs.split(",").length>3){//如果访问的图片超过3次了
    imgs = imgs.substring(imgs.indexof(",")+1, imgs.length());
   }
   */
   }
   c.setvalue(imgs);//更新
   c.setmaxage(60*60*24*30);
   c.setpath("/");//相当于把访问权限完全放开,即所有的项目都能访问
   response.addcookie(c);
   boo=true;
   break;
  }
  }
 }
 if(boo==false){//表示首次访问,即浏览器中没有图片浏览的cookie
  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();
 }

}


 

演示结果:

详细学习Java Cookie技术(用户登录、浏览、访问权限)

6、测试火狐浏览器到底支持多少个cookie和一个cookie最大为多大

index.jsp:

<a href="servlet/howmanycookieservlet">测试火狐浏览器到底支持多少个cookie和一个cookie最大为多大 </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();

 /*
 //测试个数--火狐47.0.1 最大支持110个
 for(int i=1;i<=110;i++){
  cookie c = new cookie("textnum"+i, ""+i);
  c.setmaxage(60*15);
  c.setpath("/");
  response.addcookie(c);
 }
 */

 //测试大小 ---4092字节为最大支持的单个cookie存储
 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();//读取cookie
 if(cs!=null){//防范一下
  for(cookie cc:cs){
  string key = cc.getname();
  string val = cc.getvalue();
  out.print(key+"="+val+" ");
  }
 }

 }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。