博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
web cookie and session
阅读量:6879 次
发布时间:2019-06-27

本文共 6393 字,大约阅读时间需要 21 分钟。

一、什么是会话?

  打开一个浏览器,访问多个网址后,再关掉浏览器,这一整个过程就是会话。

二、cookie技术

  这是客户端保存临时数据的技术,主要用于保存用户的登录信息及其它需要保存的数据,如购买与结帐两个servlet之间的需要传送的数据。原理是将得到的数据存在缓存或保存在本地硬盘,下次再次访问时,将cookie里的数据一并传送给服务器。

三、session技术

  作用与cookie一样,这个是服务器端技术。服务端为每一个浏览器创建一个session对象,在需要保存数据的时候,将数据存入session, 当来自该浏览器的下一个请求来时,从对应的session里取出数据使用。

  一般来说,一个浏览器启动时会有一个打开窗口,它对应一个会话session,同一个窗口内的所有选项卡共享一个session,由窗口中的超链接新打开的窗口与它的父窗口共享一个session。

  注:浏览器在关掉时,表示一个会话完结,此次会话所创建的session会被清除。除此之外,在session创建后30分钟,一样会被服务器删除。

  如何设置session的存活时间

  1.可在web.xml文件里配置session的存活时间。

//配置session的存活时间为10分钟
10

  2. 代码实现

HttpSession session = request.getSession();    session.setMaxInactiveInterval(60); //设置存活时间    session.invalidate(); //立即销毁session
  request.getSession()在执行时,如果用户对应的浏览器没有session对象,服务器则创建一个,如果已存在已创建好的session对象,则直接取出session对象使用。   request.getSession(false)则表示如果没有已存在的session对象的时候,不会创建新的session对象,只用在只需要获取session的情况下。

  由上图可知,各个用户(浏览器)在访问的时候,每次都能准确地找到自己对应的session,是因为通过cookie技术传送session ID找到的,看下图

  默认的情况下,服务器回写给客户端的cookie没有设有效时间,当浏览器被关掉时,cookie也会被删掉,因此,再打开一个新的浏览器时,由于没有cookie,服务器会新建一个session。如果让浏览器在关掉的时候仍然能获取到之前的session ID,只有回写一个带时间的cookie,一般设时间为30分钟(与session存活时间一致)。

HttpSession session = request.getSession();        String id = session.getId();        //模仿原来的cookie        Cookie cookie = new Cookie("JSESSIONID", id);        cookie.setPath("/web_study");        cookie.setMaxAge(30*60); //30 minutes        response.addCookie(cookie);

四 怎么处理禁止了cookie的情况

  session与cookie技术主要用在电子商务上,如网上商场的购买与结帐活动。如果用户在不知情的情况下禁止了cookie或在很久以前禁止了cookie而忘记打开,这样的情况用户还能正常购买吗?不可以,但是作为商场软件的开发肯定希望解决这一问题,让用户在不知情的情况下仍能正常进行购买活动。

  解决的原理就是,如cookie被禁止,则通过参数的形式将购买产生的数据传递给结帐页面。

  先看一个普通的示例

//首页 public class Welcome 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("buy"); out.println("pay"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); }}
//购买页面,这里没有显示public class Buy extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        HttpSession session = request.getSession();        String id = session.getId();        //模仿原来的cookie        Cookie cookie = new Cookie("JSESSIONID", id);        cookie.setPath("/web_study");        cookie.setMaxAge(30*60); //30 minutes        response.addCookie(cookie);        session.setAttribute("name", "iphone 6 plus");    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        this.doGet(request, response);    }}
//支付页面public class Pay extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        HttpSession session = request.getSession();        String product = (String) session.getAttribute("name");        PrintWriter out = response.getWriter();        out.print("the products you have bought:" + product);    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        this.doGet(request, response);    }}

  如果禁止了cookie后,在主页通过传递数据的方式给购买或支付页面(这里传的是jsessionid),如

out.println("buy");

  但是在实际操作的时候,不用这么麻烦,sun公司为我们提供了一个更好用的函数 response.encodeUrl(),API 说明如下

encodeURLString encodeURL(String url)Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL. For example, if the browser supports cookies, or session tracking is turned off, URL encoding is unnecessary. For robust session tracking, all URLs emitted by a servlet should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies. Parameters:url - the url to be encoded. Returns:the encoded URL if encoding is needed; the unchanged URL otherwise.

  翻译出来就是:这个函数能够智能地判断是否需要encode URL,如果浏览器支持cookie,这个函数将不起任何作用;如果浏览器不支持cookie,则将sessionid添加到URL里。

  改写后的主页面

public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        response.setContentType("text/html;charset=utf-8");        PrintWriter out = response.getWriter();        String buyUrl = response.encodeURL("/web_study/servlet/Buy");        String payUrl = response.encodeURL("/web_study/servlet/Pay");        out.println("buy");        out.println("pay");    }

五 示例

  1. cookie技术

  下例演示的是如何保存历史访问时间

package cn.blueto.study;import java.io.IOException;import java.io.PrintWriter;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 CookieDemo extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        response.setCharacterEncoding("UTF-8");        response.setContentType("text/html; charset=UTF-8");                PrintWriter out = response.getWriter();        out.print("你上次访问的时间:");                Cookie cookies[] = request.getCookies();                for(int i = 0 ; cookies != null && i < cookies.length; i++){            if (cookies[i].getName().equals("lastAccessTime")){                long cookiesValse = Long.parseLong(cookies[i].getValue());                Date d = new Date(cookiesValse);                out.print(d.toLocaleString());            }        }                Cookie cookie = new Cookie("lastAccessTime", System.currentTimeMillis()+"");        cookie.setMaxAge(30*24*3600); // one month      //如果要删除cookie,只需要将时间设为0      //cookie.setMaxAge(0);         cookie.setPath("/web_study");        response.addCookie(cookie);    }        public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        this.doGet(request, response);    }}

 

转载于:https://www.cnblogs.com/lovemo1314/p/4691062.html

你可能感兴趣的文章
序列化模块、导入模块
查看>>
thinkphp3.1课程 1-1 为什么thinkphp在开发好后需要关掉开发模式
查看>>
用 Flask 来写个轻博客 (13) — M(V)C_WTForms 服务端表单检验
查看>>
Teradata 语句简单优化
查看>>
c# 通过关键字查询
查看>>
已知一个字符串S 以及长度为n的字符数组a,编写一个函数,统计a中每个字符在字符串中的出现次数...
查看>>
jquery
查看>>
伏地魔
查看>>
linux
查看>>
安装虚拟机-linux系统步骤
查看>>
集训第五周动态规划 J题 括号匹配
查看>>
微信小程序车牌键盘
查看>>
python 网络编程
查看>>
【BZOJ】2165: 大楼
查看>>
【BZOJ】2442: [Usaco2011 Open]修剪草坪
查看>>
2分钟读懂UML
查看>>
Curso de FP Interpretacion Lenguaje de Signos a distancia.
查看>>
HTML图像
查看>>
类和对象简析
查看>>
深入Java集合学习系列:LinkedHashSet的实现原理
查看>>