cookie与session有什么关系,token又是干嘛用!!

cookie是什么,它与session有什么关系?

cookie是一个保存在客户机中的简单的文本文件,一般保存了与web服务器交互的信息,比如说用户信息、商品加入购物车的信息等等,由于http是无状态连接的,所以要有会话session,web服务器才能区分不同的用户。

Cookie创建

后台直接设置,一种是直接设置;一种是隐含设置,调用request.getSession()或者访问jsp页面。

//第一种写法
Cookie cookie = new Cookie("test","123");
 cookie.setPath("/");
 cookie.setMaxAge(60);//1分钟
 cookie.setDomain("localhost");
 cookie.setHttpOnly(true);
 response.addCookie(cookie);

 //第二种写法
 StringBuffer stringBuffer = new StringBuffer();
 stringBuffer.append("test=").append(123).append(";");
 stringBuffer.append("Path=/;");
 response.setHeader("Set-Cookie",stringBuffer.toString());

隐含设置调用request.getSession()

//Request 类
 this.session = manager.createSession(sessionId);
 if (this.session != null && this.getContext() != null && this.getContext().getServletContext().getEffectiveSessionTrackingModes().contains(SessionTrackingMode.COOKIE)) {
      Cookie cookie = ApplicationSessionCookieConfig.createSessionCookie(context, this.session.getIdInternal(), this.isSecure());
      this.response.addSessionCookieInternal(cookie);
  }

//shiro中创建cookie信息
AbstractNativeSessionManager:
public Session start(SessionContext context) {
   Session session = this.createSession(context); //创建simpleSession
     this.applyGlobalSessionTimeout(session);
     this.onStart(session, context);
     this.notifyStart(session);//通知
     return this.createExposedSession(session, context);
 }
 
DefaultWebSessionManager:
protected void onStart(Session session, SessionContext context) {
    super.onStart(session, context);
    if (!WebUtils.isHttp(context)) {
        log.debug("SessionContext argument is not HTTP compatible or does not have an HTTP request/response pair. No session ID cookie will be set.");
    } else {
        HttpServletRequest request = WebUtils.getHttpRequest(context);
        HttpServletResponse response = WebUtils.getHttpResponse(context);
        if (this.isSessionIdCookieEnabled()) {
            Serializable sessionId = session.getId();
            this.storeSessionId(sessionId, request, response);//将sessionid保存到cookie
        } else {
            log.debug("Session ID cookie is disabled.  No cookie has been set for new session with id {}", session.getId());
        }

        request.removeAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE);
        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_IS_NEW, Boolean.TRUE);
    }
}

Token的产生

随着用户数越来越多,如果采用session保存用户信息,会给到服务很大的压力,所以基于token的是身份验证应用而生。用户登陆成功后,后端生成token,然后返回给用户端,由用户端保存这个token信息,往后请求都包这个toke参数带上,这个比传统session性能更佳,对于分布式应用也有更好的支持。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值