java中Cookie类详解

avatar 2017年07月08日20:54:14 2 2800 views
博主分享免费Java教学视频,B站账号:Java刘哥

一、cookie的操作

对Cookie的操作无外乎三部分:读、分析、写。

写Cookie

Cookie theCookie = new Cookie(“username” , “Tom”); response.addCookie(theCookie); 当Servlet向客户端写Cookie时,还可以通过Cookie类的setMaxAge(intexpiry)方法来设置Cookie的有效期。参数expiry以秒为单位,它具有以下含义: ·如果expiry大于零,就指示浏览器在客户端硬盘上保存Cookie的时间为expriy秒。 ·如果expiry等于零,就指示浏览器删除当前Cookie。 ·如果expiry小于零,就指示浏览器不要把Cookie保存到客户端硬盘。Cookie仅仅存在于当前浏览器进程中,当浏览器进程关闭,Cookie也就消失。 Cookie默认的有效期为-1。对于来自客户端的Cookie,Servlet可以通过Cookie类的getMaxAge()方法来读取Cookie的有效期。

读取分析客户端Cookie

Cookie[] cookies = request.getCookies(); HttpServletRequest类的getCookies()方法返回一个Cookie数组,它包含了HTTP请求中的所有Cookie。如果在HTTP请求中没有任何Cookie,那么getCookies()方法返回null。 对于每个Cookie对象,可调用getName()方法来获得Cookie的名字,调用getValue()方法来获得Cookie的值。  

二、常用的Cookie类方法

String getName()   用于返回Cookie的名称 void setValue(String name)    用于设置Cookie的值 String getName()    用于返回Cookie的值 void setMaxAge(int expiry)    用于设置Cookie在浏览器客户端上保存的秒数 int getMaxAge()     用于获取Cookie在浏览器客户端上保存的秒数 void setPath(String uri)    用于设置该Cookie项的有效目录路径 String getPath()    用于获取该Cookie项的访问目录路径 void setDomain(String pattern)    用于设置该Cookie项的有效域 String getDomain()    用于返回该Cookie的项有效域 void setVersion(int v)    用于设置该Cookie采用的项协议版本 int getVersion()    用于返回该Cookie项采用的协议版本 void setComment(String purpose)    用于设置该Cookie项的注解部分 String getComment()    用于返回该Cookie项的注解部分 void setSecure(boolean flag)    用于设置该Cookie项是否只能采用安全协议传送 boolean getSecure()    用于返回该Cookie项是否只能使用安全的协议传送  

三、Cookie案例(1)——显示用户上次访问时间

(1)新建 LastAcessServlet 类

老规矩,还是在 Servlet 项目下,新建 com.liuyanzhao 包,然后新建LastAcessServlet.java
  1. package com.liuyanzhao;
  2. import java.io.IOException;
  3. import java.text.SimpleDateFormat;
  4. import java.util.Date;
  5. import javax.servlet.ServletException;
  6. import javax.servlet.http.Cookie;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. import org.apache.jasper.tagplugins.jstl.core.Out;
  11. /*
  12.  * @author LiuYanzhao 
  13.  */
  14. public class LastAcessServlet extends HttpServlet{
  15.     private static final long serialVersionUID = 1L;
  16.     public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
  17.         //指定服务器输出内容的编码方式为UTF-8,防止乱码
  18.         response.setContentType("text/html;charset=utf-8");
  19.         /*
  20.          * 设定与个人cookie的name为:lastAcessTime
  21.          * 读取客户端发送的cookie获得用户上次访问的时间显示
  22.          */
  23.         String lastAcessTime = null;
  24.         //获取所有cookie,并将这些cookie存放在数组中
  25.         Cookie[] cookies = request.getCookies();
  26.         for(int i=0;cookies!=null && i<cookies.length;i++) {
  27.             if("lastAcess".equals(cookies[i].getName())) {
  28.                 //如果cookie名称为lastAcess,则获取该cookie的值
  29.                 lastAcessTime = cookies[i].getValue();
  30.                 break;
  31.             }
  32.         }
  33.         //判断是否存在名称为lastAcess的cookie
  34.         if(lastAcessTime==null) {
  35.             response.getWriter().print("您是首次访问本站");
  36.         } else {
  37.             response.getWriter().print("您上次访问本站的时间是:"+lastAcessTime);
  38.         }
  39.         //创建cookie,将当前时间作为cookie的值发送给客户端
  40.         String currentTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
  41.         Cookie cookie = new Cookie("lastAcess", currentTime);
  42.         cookie.setMaxAge(60*60);
  43.         //发送cookie
  44.         response.addCookie(cookie);
  45.     }
  46.     protected void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
  47.         this.doPost(req, resp);
  48.     }
  49. }

(2在 web.xml 里添加 LastAcessServlet 映射

  1. <servlet>
  2.     <servlet-name>LastAcessServlet</servlet-name>
  3.     <servlet-class>com.liuyanzhao.LastAcessServlet</servlet-class>
  4. </servlet>
  5. <servlet-mapping>
  6.     <!-- 映射为 LastAcessServlet -->
  7.     <servlet-name>LastAcessServlet</servlet-name>
  8.     <url-pattern>/LastAcessServlet</url-pattern>
  9. </servlet-mapping>

(3)重启 Tomcat , 打开浏览器

①在浏览器输入:http://localhost:8080/ServletTest/LastAcessServlet ②刷新浏览器或者关闭浏览器,重新输入刚才的 url     本文链接:https://liuyanzhao.com/4905.html  
  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:1   待审核评论数:0
  1. avatar 昆山装饰

    默默的来默默的走!