JAVAWEB——会话技术Cookie&Session,Cookie&Session的具体用法,获得Session对象,Session的生命周期

一、 会话技术简介

1. 存储客户端的状态

我们在网站的购物系统,用户将购买的商品信息存储到哪里?因为Http协议是无状态的,也就是说每个客户访问服务器端资源时,服务器并不知道该客户端是谁,所以需要会话技术识别客户端的状态。会话技术是帮助服务器记住客户端状态(区分客户端)

2.会话技术

从打开一个浏览器访问某个站点,到关闭这个浏览器的整个过程,成为一次会话。会话技术就是记录这次会话中客户端的状态与数据的。
会话技术分为CookieSession

  • Cookie:数据存储在客户端本地,减少服务器端的存储的压力,安全性不好,客户端 可以清除cookie。
  • Session:将数据存储到服务器端,安全性相对好,增加服务器的压力。

二、 Cookie技术

举个例子我们在逛淘宝网站:
在这里插入图片描述
该图表述了,当我们使用浏览器去访问购物网站,把东西加入到购物车的时候,会将商品信息,放到浏览器中。当我们关闭浏览器,再次进行访问的时候,放在购物车的商品仍然显示。

Cookie技术是将用户的数据存储到客户端的技术,我们分为两方面学习:

第一,服务器端怎样将一个Cookie发送到客户端。
第二,服务器端怎样接受客户端携带的Cookie。

引出下面两大点内容:

三、 服务器端向客户端发送一个Cookie

1.创建Cookie:

  • Cookie cookie = new Cookie(String cookieName,String cookieValue);

例如:

Cookie cookie = new Cookie("username""zhangsan");

那么该cookie会以响应头的形式发送给客户端:
在这里插入图片描述

注意:Cookie中不能存储中文

2.设置Cookie在客户端的持久化时间:

  • cookie.setMaxAge(int seconds); 这里括号的时间秒

例如:

cookie.setMaxAge(10*60);

设置cookie信息在浏览器的磁盘文件中存储的时间是10分钟,过期浏览器自动删除该cookie信息

注意:如果不设置持久化时间,cookie会存储在浏览器的内存中,浏览器关闭 cookie信息销毁(会话级别的cookie),如果设置持久化时间,cookie信息会根据时间长短被持久化到浏览器的磁盘文件里。

3. 设置Cookie的携带路径:

  • cookie.setPath(String path);
    注意:如果不设置携带路径,那么该cookie信息会在访问产生该cookie的 web资源所在的路径都携带cookie信息

例如:

cookie.setPath("/WEB16");

代表访问WEB16应用中的任何资源都携带cookie

cookie.setPath("/WEB16/cookieServlet");

代表访问WEB16中的cookieServlet时才携带cookie信息

4. 向客户端发送cookie:

  • response.addCookie(Cookie cookie);

5. 删除客户端的cookie:

如果想删除客户端的已经存储的cookie信息,那么就使用同名同路径的持久化时间为0的cookie进行覆盖即可

综合案例一:

@WebServlet(name = "SendCookieServlet",urlPatterns ="/SendCookieServlet")
public class SendCookieServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request,response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //1.创建Cookie对象
        Cookie cookie = new Cookie("name","zhangsan");
        //1.1 为Cookie设置持久化时间---Cookie信息在硬盘上保存的时间
        cookie.setMaxAge(60*10);//10分钟,时间设置为0代表删除该Cookie
        //1.2为Cookie设置携带路径
        cookie.setPath("/SendCookieServlet");//访问SendCookieServlet资源才携带Cookie
        cookie.setPath("/WEB16");//访问WEB16下的任何资源是都携带这个Cookie
        cookie.setPath("/");//访问服务器下的所有资源携带的Cookie
        //2.发送Cookie中存储的信息发的送到客户端====以响应头的形式
        response.addCookie(cookie);
    }
}

综合案例二:

(删除Cookie)

@WebServlet(name = "RemoveCookieServlet",urlPatterns =
"/RemoveCookieServlet")
public class RemoveCookieServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
            doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
            //删除客户端保存name=zhangsan的cookie信息
        Cookie cookie = new Cookie("name","");
            //将path设置成与要删除cookie的path一致
            cookie.setPath("/WEB16");
            //设置时间为0
            cookie.setMaxAge(0);
            response.addCookie(cookie);
    }
}

使用步骤:如果我们此时访问”/SendCookieServlet”,那么name =zhangsan会存放到Cookie中,随后我们访问“/RemoveCookieServlet“的时候,我们会清空其缓存,只要设置他的MaxAge=0即可。我们访问index.jsp并不会查找出Cookie。

四、 服务器端怎么接受客户端携带的Cookie

cookie信息是以请求头的方式发送到服务器端的。所以我们服务端去接受Cookie的使用步骤:

  • 第一步:通过request获得所有的Cookie:
Cookie[] cookies = request.getCookies();
  • 第二步:遍历Cookie数组,通过Cookie的名称获得我们想要的Cookie
for(Cookie cookie : cookies){
    
    
if(cookie.getName().equal(cookieName)){
    
    
String cookieValue = cookie.getValue();
}
}

案例:

@WebServlet(name = "GetCookieServlet",urlPatterns =
"/GetCookieServlet")
public class GetCookieServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //获取客户端携带的cookie的数据
         Cookie cookies[] = request.getCookies();
         //通过cookie名称获取想要的Cookie
        for (Cookie cookie :cookies){
    
    
            //获得cookie的名称
            String cookieName = cookie.getName();
            if (cookieName.equals("name")){
    
    
                String cookieValue = cookie.getValue();
                System.out.println(cookieValue);
            }
        }
    }

五、 Session技术

Session技术是将数据存储在服务器端的技术,会为每个客户端都创建一块内存空间存储客户的数据,但客户端需要每次都携带一个标识ID去服务器中寻找属于自己的内存空间。所以说Session的实现是基于CookieSession需要借助于Cookie存储客户的唯一性标识JSESSIONID
在这里插入图片描述
在Session这我们需要学习如下三个问题:

怎样获得属于本客户端的session对象(内存区域)?

怎样向session中存取数据(session也是一个域对象)?

session对象的生命周期?

1. 获得Session对象

  • HttpSession session = request.getSession()
    此方法会获得专属于当前会话的Session对象,如果服务器端没有该会话的Session 对象会创建一个新的Session返回,如果已经有了属于该会话的Session直接将已有的Session返回(实质就是根据JSESSIONID判断该客户端是否在服务器上已经存在 session了

案例一:

@WebServlet(name = "SessionServlet1",urlPatterns ="/SessionServlet1")
public class SessionServlet1 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
            doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
   //创建属于该客户端(会话)的私有的session区域
   /*request.getSession()方法内部会判断 该客户端是否在服务器端已经存在session
 如果该客户端在此服务器不存在session,那么就会创建一个新的session对象
 如果该客户端在此服务器已经存在session 获得已经存在的session并返回*/
    HttpSession httpSession =  request.getSession();
    String id = httpSession.getId();//该session对象的编号id
       response.getWriter().write("JSESSIONID:"+id);
            System.out.println(id);
     }
}

效果如下:
在这里插入图片描述

2. 怎样向session中存取数据(session也是一个域对象)

Session也是存储数据的区域对象,所以session对象也具有如下三个方法:

  • session.setAttribute(String name,Object obj)
  • session.getAttribute(String name)
  • session.removeAttribute(String name)

案例二:

第一步:创建一个SessionServlet1对象

@WebServlet(name = "SessionServlet1",urlPatterns =
"/SessionServlet1")
public class SessionServlet1 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
            doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
  HttpSession httpSession =  request.getSession();
  httpSession.setAttribute("name","yjw");
  String id = httpSession.getId();//该session对象的编号id
         response.getWriter().write("JSESSIONID:"+id);
            System.out.println(id);
        }
}

第二步:创建一个SessionServlet2

@WebServlet(name = "SessionServlet2",urlPatterns = "/SessionServlet2")
public class SessionServlet2 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
            doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //从session中获得存储数据
         HttpSession httpSession = request.getSession();
         String attribute =(String)httpSession.getAttribute("name");
         response.getWriter().write(attribute);
    }
}

效果如下:
在这里插入图片描述

3. Session对象的生命周期(面试题/笔试题)

Session对象的生命周期

  • 创建:第一次执行request.getSession()时创建
  • 销毁:
  1. 服务器(非正常)关闭时
  2. session过期/失效(默认30分钟)
    注意:时间的起算点,从不操作服务器端的资源开始计时30分钟可以在工程的web.xml中进行配置

如下:

<session-config>
        <session-timeout>60</session-timeout>
</session-config>
  1. 手动销毁session
  • session.invalidate()

Session作用范围:
默认在一次会话中,也就是说在,一次会话中任何资源公用一个session对象

面试题:浏览器关闭,session就销毁了?——不对
浏览器是在客户端级别,而session是在服务器级别

4. JSESSIONID的持久化问题

思想:将访问的第一个Servlet自动设置的Session,以Cookie的形式,改变setMaxAge()在客户端存取的时长。从而实现JSESSIONID的持久化。

@WebServlet(name = "SessionServlet1",urlPatterns =
"/SessionServlet1")
public class SessionServlet1 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
            doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
HttpSession httpSession =  request.getSession();
String id = httpSession.getId();//该session对象的编号id
//手动创建一个存储JSESSIONID的Cookie为该Cookie设置持久化时间
 Cookie cookie = new Cookie("JSESSIONID",id);
        cookie.setPath("/WEB16");
        cookie.setMaxAge(60*10);//自行设置时间
        response.addCookie(cookie);         
        response.getWriter().write("JSESSIONID:"+id);
           System.out.println(id);
       }
}

猜你喜欢

转载自blog.csdn.net/Mr_GYF/article/details/109169158