美文网首页
Cookie与Session的区别:

Cookie与Session的区别:

作者: 小牛长成记 | 来源:发表于2018-10-08 21:21 被阅读0次

优缺点:
Cookie:节省了服务器资源,但是存储在浏览器缓存数据不安全。
session:存储在数据库中,数据安全,消耗的是服务器的资源。

Session是当有用户访问服务器时,tomcat服务器自动创建的Session,并且servlet是单实例,只创建一个Session对象。如果需要用Session直接用request方法获取Session即可。

  HttpSession session = request.getSession();
        session.setAttribute("check", check);

Cookie是New出来的,是需要我们自己创建cookie来获取Cookie对象的,可以随意的创建,并不像Session一样是单实例。

下面的实例是创建Cookie,Cookie没有无参的构造方法!cookie有两个参数的构造方法,cookie(String key,String value) ,下面的实例key就是user ,value中封装了username,userpwd 两个参数,并且用“_”进行连接。

        // 创建Cookie
        Cookie cookie = new Cookie("user", URLEncoder.encode(check.getUserName(), "utf-8")
                + "_" + URLEncoder.encode(check.getUserPwd(), "utf-8"));
        String remember = request.getParameter("remberMe");
        if (remember != null) {
            // 保存时间
            cookie.setMaxAge(60 * 60 * 24 * 7);
        } else {
            cookie.setMaxAge(0);
        }
        //setPath
        cookie.setPath("/");
        // 将数据发送到客户端
        response.addCookie(cookie);

在view层中需要接收cookie中保存的数据:通过request.getCookies();方法即可获得cookie[]数组

    //得到cookie数组
    Cookie[] cookies = request.getCookies();
    String username = "";
    String password = "";
    String checked = "" ;
    if(cookies != null){
        for (Cookie cookie : cookies) {
            if("user".equals(cookie.getName())){
                String value = cookie.getValue();
                //通过String的split方法,以"_" 进行分割,得到一个String[]数组
                String[] res = value.split("_");
               //用URLDecoder方法进行解码。
                username = URLDecoder.decode(res[0], "utf-8");
                password = URLDecoder.decode(res[1], "UTF-8");
                checked = "checked = checked";
                
            }
        }

相关文章

网友评论

      本文标题:Cookie与Session的区别:

      本文链接:https://www.haomeiwen.com/subject/olujaftx.html