Session:
服务器会给每个用户(浏览器)创建一个 Session 对象
一个 Session 独占一个浏览器,只要浏览器没有关闭,这个 Session 就存在
代码如下:
- package com.demo.cookie;
-
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- import java.io.IOException;
-
- public class Session extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
-
- //解决中文乱码
- req.setCharacterEncoding("UTF-8");
- resp.setCharacterEncoding("UTF-8");
- resp.setContentType("text/html");
-
- //得到Session
- HttpSession session = req.getSession();
-
- //给Session中存东西
- session.setAttribute("name","hhh");
-
- //获取Session的ID
- String id = session.getId();
-
- //判断Session是否是新创建的
- if (session.isNew()){
- resp.getWriter().write("Session创建,ID:"+id);
- }else {
- resp.getWriter().write("Session已经在服务器存在,ID:"+id);
- }
-
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- doGet(req, resp);
- }
- }
web.xml 注册:
- <servlet>
- <servlet-name>seservlet-name>
- <servlet-class>com.demo.cookie.Sessionservlet-class>
- servlet>
- <servlet-mapping>
- <servlet-name>seservlet-name>
- <url-pattern>/seurl-pattern>
- servlet-mapping>
运行后查看结果
应用程序存入 SessionID

请求头存入 SessionID

注销 Session:
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- HttpSession session = req.getSession();
- session.removeAttribute("name");
- //手动注销Session
- session.invalidate();
- }
进入注销页再进入 SessionID 页,SessionID 改变
还可以设置 Session 默认失效时间
-
- <session-config>
-
- <session-timeout>15session-timeout>
- session-config>
Session 与 Cookie 的区别:
1. Cookie 是把用户的数据写给用户的浏览器,浏览器保存,可以保存多个
2. Session 把用户的数据写到用户独占 Session 中,服务器端保存(保存重要的信息,减少服务器资源的浪费)
3. Session 对象由服务器创建
服务器中的 Session 可以存东西,客户端向服务器发起请求,将登记一个 Session
用户拿到的是 SessionID,每个用户唯一