JavaWeb-Session-Cookie

116 阅读1分钟

Cookie

what

  • 在设置cookie的时候,是通过响应头里的Set-Cookie来设置
  • 在使用的时候,请求头里带上cookie发给web服务器
  • 说白了,这个东西就是个头信息
  • cookie会保存在客户端浏览器上。

use

在学习Servlet相关的源码的时候,看到Cookie这个类的源码时,其中的注释说的很明白什么时cookie了。同时源码中也说了如何使用。

  • The servlet sends cookies to the browser by using the HttpServletResponse.addCookie(javax.servlet.http.Cookie)
  • cookie是由servlet在返回响应的时候给浏览器的。
  • Cookies can be retrieved from a request by using the HttpServletRequest.getCookies() method.
  • 在浏览器发出请求时,servlet可以通过request拿出请求中的cookie

Session

what

同理:学习HttpSession这个源码,看源码注释。

Provides a way to identify a user across more than one page request 
or visit to a Web site and to store information about that user.
  • 用来表示每个用户的。并且session不是在客户端,在服务端。

use

如何用这玩意。http是无状态的

  • session是有id的。想像成kv的。
  • 第一次请求的时候,会给浏览器一个cookie名字为:JSESSIONID。这个就是标示该用户的sessionID
  • 服务器通过cookie带来的sessionID就能进行相应的逻辑了。
  • tomcat正常停止时会持久化session。

分布式Session

后续。。