self-confidence,the source of all the power

导航

web cookie and session

一、什么是会话?

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

二、cookie技术

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

三、session技术

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

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

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

  如何设置session的存活时间

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

//配置session的存活时间为10分钟
<session-config>
    <session-timeout>10</session-timeout>
</session-config>

  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("<a href = '/web_study/servlet/Buy'>buy</a>"); out.println("<a href = '/web_study/servlet/Pay1'>pay</a>"); } 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("<a href =  '/web_study/servlet/Buy?JSESSIONID="request.getSession().getId()+"'>buy</a>");

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

encodeURL
String 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("<a href =  '"+buyUrl+"'>buy</a>");
        out.println("<a href =  '"+payUrl+"'>pay</a>");
    }

五 示例

  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); } }

 

posted on 2015-07-31 00:47  漩涡鸣人  阅读(401)  评论(0编辑  收藏  举报