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性能更佳,对于分布式应用也有更好的支持。