浅谈Cookie和Session的初步理解

浅谈Cookie和Session的初步理解

前言

       HTTP是无状态的协议,客户每次读取web页面时,服务器都打开新的连接,而且服务器也不会自动维护客户的上下文信息。那么要怎么才能在多次请求之间共享信息呢?

       session和cookie就是为解决HTTP协议的无状态采用的两种解决方案。Cookie是将信息保存在客户端解决,而session则是将信息保存到服务器端解决~

       Cookie对象与HttpSession对象的作用是维护客户端浏览器与服务端的会话状态的两个对象。由于HTTP协议是一个无状态的协议,所以服务端并不会记录当前客户端浏览器的访问状态,但是在有些时候我们是需要服务端能够记录客户端浏览器的访问状态的

Cookie

       Cookie是一种保存少量信息至浏览器的一种技术,第一次请求时,服务器会响应给浏览器一些Cookie信息,第二次请求,浏览器会携带之前的cookie 发送给服务器,通过这种机制可以实现在浏览器端保留一些用户信息。为服务端获取用户状态获得依据

获取Cookie

public class Create_Cookie extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建Cookie
        Cookie username = new Cookie("username","alvin");
        //设置Cookie的持久化时间
        username.setMaxAge(120);
        Cookie password = new Cookie("password","123456");
        //设置Cookie的提交路径限定
        password.setPath("/aaa/bbb");
        Cookie age = new Cookie("age","10");
        Cookie gender = new Cookie("gender", URLEncoder.encode("男","UTF-8"));
        //将cookie响应给浏览器,将cookie放入响应对象中
        response.addCookie(username);
        response.addCookie(password);
        response.addCookie(age);
        response.addCookie(gender);
    }
}

提交Cookie

public class TestCookie extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //通过HttpServletRequest对象获取Cookie,返回Cookie数组
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie : cookies){
            if(cookie.getName().equals("gender")){
                System.out.println(cookie.getName() + ":" + URLDecoder.decode(cookie.getValue(),"UTF-8"));
            }else{
                System.out.println(cookie.getName() + ":" + cookie.getValue());
            }
        }
    }
}

持久化Cookie和状态Cookie

状态Cookie

       浏览器会缓存Cookie对象,当浏览器被关闭后则会被销毁

持久化Cookie

       浏览器会对Cookie做持久化处理,基于文件形式保存在系统的指定目录中。在Windows10系统中为了安全问题不会显示Cookie中的内容

Cookie总结

       当Cookie对象创建后默认为状态Cookie。可以使用Cookie对象下的cookie.setMaxAge(60)方法设置失效时间,单位为秒。一旦设置了失效时间,那么该Cookie为持久化Cookie,浏览器会将Cookie对象持久化到磁盘中。当失效时间到达后文件删除。

       Cookie对于存储内容是基于明文的方式存储的,所以安全性很低。不要在Cookie中存放敏感数据。在数据存储时,虽然在Servlet4.0中Cookie支持中文,但是建议对Cookie中存放的内容做编码处理,也可提高安全性。

Session

Session引入和使用

       首次访问服务器上的一个JSP页面时,JSP引擎产生一个session对象,每个session都会有一个sessionid,然后会将数据保存到服务器端,而sessionid会被保存在客户端的Cookie中。后续每次请求request都会携带cookie到服务器端,服务器端就会根据客户端的sessionid判断属于哪个会话。

       如果客户的浏览器不支持cookie,则服务器无法将id存放到客户端,就不能建立session对象和客户的一 一对应关系。这时就需要URL重写来实现session对象的唯一性。所谓URL重写,就是当客户从一个页面重新连接到另外一个页面时,通过向这个新的URL添加参数,把ression对象的id传带过去,这样就可以保障客户在该对站各个页面中的session对象是完全相同的。

Session和Cookie的区别

       单个cookie保存的数据不能超过4K,很多浏览器都限制一个域名保存cookie的数量。而HttpSession没有容量以及数量的限制。

       cookie数据存放在客户端,session数据放在服务器上(sessionid可以通过cookie保存在客户端,也可以使用URL重写方式)

       cookie不是很安全(可以加密),别人可以分析存放在本地的cookie并进行cookie欺骗,考虑到安全应当使用session

       session会在一定时间内保存在服务器上。当访问增多,会比较占用你服务器的性能,考虑到减轻服务器性能方面,应当使用cookie

通过Session判断用户是否登录

登录成功将用户信息存户HttpSession,否则回到登录页
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("pwd");
        if("alvin".equals(username) && "123456".equals(password)){
            // 将当前用户保存进入HttpSession
            User user =new User(username,password);
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            // 跳转至WEB-INF/welcome.html
            request.getRequestDispatcher("WEB-INF/welcome.html").forward(request,response);
        }else{
            // 登录失败,回到index,jsp
            response.sendRedirect("index.jsp");
        }
    }
用来向welcome.html中跳转的,同时验证登录,登录过,可以直接跳转,否则回到登录页
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 判断是否已经登录
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        // 如果登录过,直接跳转
        if(null != user){
            request.getRequestDispatcher("WEB-INF/welcome.html").forward(request,response);
        }else{
            // 没登录过,跳转至登录页
            response.sendRedirect("index.jsp");
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_41424688/article/details/108416637