2阶——Session 与 Cookie

因为Http协议是无状态的(即第一次请求访问 和第二次请求访问之间的数据不能进行交互)所以产生了Cookie 和session

1.Cookie

 cookie值的格式是key=value;key2=value2   (tomcat8之后cookie支持存储中文数据)

Cookie的默认时效为Session,也就是说浏览器关闭,Cookie会和session一起失效,但是Cookie的有效时间是可以设置的。

Cookie有一个属性expires,设置其值为一个时间,那么当到达此时间后,此cookie失效

Cookie诞生的最初目的是为了存储web中的状态信息,以方便服务器端使用。比如判断用户是否是第一次访问网站

执行流程:

1)、首先,客户端会发送一个http请求到服务器端。

2)、服务器端接受客户端请求后,发送一个http响应到客户端,这个响应头,其中就包含Set-Cookie头部,浏览器保存Cookie

3)、浏览器第二次访问,将保存的cookie发给后台,后台识别并更新cookie,返回浏览器再次保存。

服务器端像客户端发送Cookie是通过HTTP响应报文实现的,在Set-Cookie中设置需要像客户端发送的cookie,cookie格式如下:

Set-Cookie: "name=value;domain=.domain.com;path=/;expires=Sat, 11 Jun 2016 11:29:42 GMT;HttpOnly;secure"

@WebServlet("/cookie1Servlet")
public class Cookie1Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");

        Cookie c = new Cookie("msg","hello");
        response.addCookie(c);


        //获取从客户端访问的cookie 如果为空的话证明是第一次访问,因为cookie是由服务器发送给客户端的并保存再客户端
        Cookie[] css = request.getCookies();
        if(css != null){
            for(Cookie c1 : css){
                System.out.println(c1.getName());
                System.out.println(c1.getValue());
            }
        }else {
            System.out.println("无cookie");
        }

        //request.getRequestDispatcher("/cookie2Servlet").forward(request,response);

    }

//记住上次访问的时间小demo

@WebServlet("/lastVisitorServlet")
public class LastVisitorServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //加入有一个cooki
        Cookie[] cookies = request.getCookies();
        System.out.println("1111");


        boolean flag = false;

        if(cookies != null) {
            for (Cookie c : cookies) {
                if (c.getName().equalsIgnoreCase("lastTime")) {
                    flag = true;
                    try {


                        //获取上次访问的时间
                        String oldtime = c.getValue();


                        //更新最新的cookie信息 并发送回去
                        Date date = new Date();
                        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String str_date = sf.format(date);

                        str_date = URLEncoder.encode(str_date,"utf-8");//编码

                        c.setValue(str_date);
                        c.setMaxAge(60 * 60 * 24);
                        //返回最新的cookie值
                        response.addCookie(c);



                        oldtime = URLDecoder.decode(oldtime,"utf-8"); //解码
                        response.getWriter().write("你上次访问的时间是:" + oldtime + "本次访问的时间为"+URLDecoder.decode(str_date,"utf-8"));

                        break;

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }




            if(cookies == null || cookies.length == 0 || flag == false){

                System.out.println("2222222222");

                Date date = new Date();
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String str_date1 = sf.format(date);

                str_date1 = URLEncoder.encode(str_date1,"utf-8"); //编码


                Cookie cookie = new Cookie("lastTime",str_date1);
                cookie.setMaxAge(60 * 60 * 24);
                response.addCookie(cookie);
                response.getWriter().write("欢迎你首次访问本网站");
            }
        }




    }
 
 
 
 
 
 
 

2.Session
Session 就是在一次会话中解决2次HTTP的请求的关联,让它们产生联系,让2两个页面都能读取到找个这个全局的session信息。session信息存在于服务器端,所以也就很好的解决了安全问题。
 
Cookie分为内存中Cookie(也可以说是进程中Cookie)和硬盘中Cookie。大部分的Session机制都使用进程中Cookie来保存Session id的,关闭浏览器后这个进程也就自动消失了,进程中的Cookie自然就消失了,那么Session id也跟着消失了,再次连接到服务器时也就无法找到原来的Session了。
也有使用硬盘中Cookie,比如说CSDN的“记住我一周”,或者我们的购物车信息可以在切换不同浏览器时依然可用。这就要用到我们上文提到的另一种Cookie了——硬盘中Cookie,这时Session id将长期保存在硬盘上的Cookie中,直到失效为止。

个人理解:
      session的本质其实就是cookie  session通过SessionId 来确认唯一,而jsessionid依靠的是cookie , 其实就可以看作cookie中存放了一个键值对: key为jsessionid  值为一个唯一的字符串。
 
 
 
 
坚持
原文地址:https://www.cnblogs.com/gaoSJ/p/12923672.html