javaweb网页会话管理http/cookie相关实例

http性质

  • http是简单的
  • http是可扩展的
  • http是无状态的、有会话的:在同一个链接中,每个请求之间是没有关系的。http本身是无状态的,使用cookies可以创建有状态的会话。

cookie是服务器发送到浏览器,并保存在浏览器端端一小块数据;浏览器下次访问该服务器时会自动携带块该数据,将其发送给服务器

demo

    //cookie
    @RequestMapping(path = "/cookie/set", method = RequestMethod.GET)
    @ResponseBody
    public String setCookie(HttpServletResponse response){
        // create cookie
        Cookie cookie = new Cookie("code", CommunityUtil.generateUUID());
        // Sets the range over which the cookie is valid
        cookie.setPath("/myCommunity/alpha");
        // if you set a lifetime of cookie, it will store in your disk
        cookie.setMaxAge(60 * 10); // 10 min
        // send cookie
        response.addCookie(cookie);

        return "set cookie";
    }

    @RequestMapping(path = "/cookie/get", method = RequestMethod.GET)
    @ResponseBody
    public String getCookie(@CookieValue("code") String code){		// 我们上边set了code的值
        System.out.println(code);

        return "get cookie";
    }

在这里插入图片描述
在这里插入图片描述

session

由于cookie是由浏览器保存在本地的,所以稳定性很低。还可以使用session来保存记录,在通信时穿一个session(cookieid),由服务器保存,以后通信时服务器自己去查找相应的cookieid

demo

    // demo of session
    @RequestMapping(path = "/session/set", method = RequestMethod.GET)
    @ResponseBody
    public String setSession(HttpSession session){
        session.setAttribute("id", 1);
        session.setAttribute("name", "Test");
        return "set session";
    }

    @RequestMapping(path = "/session/get", method = RequestMethod.GET)
    @ResponseBody
    public String getSession(HttpSession session){
        System.out.println(session.getAttribute("id"));
        System.out.println(session.getAttribute("name"));
        return "get session";
    }

set session
在这里插入图片描述

实际应用

分布式部署时使用session比较少,分布式部署通常有多台服务器,前面由nginx来负责负载均衡。
有可能浏览器第一次访问时,服务器1比较空闲,此时在服务器1创建了一个session;而当浏览器第二次访问时,不一定访问的服务器1,又要重新创建session。

解决办法:

  • 粘性session:同一个ip只给一个服务器负责。这种方法性能不好,难以保证服务器是负载均衡的
  • 同步session:一台服务器创建session,同时同步给其他服务器。影响性能,服务器耦合度高
  • 共享session:单独用一个服务器存放session,其他服务器访问该服务器获取session。但是安全度低。

主流办法是尽量用cookie,不能用cookie的就用数据库集群(redis)来保存session。
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值