渚漪Day17——JavaWeb 08【Session】

Session

  • 服务器技术,保存用户的会话信息

什么是session

  • 服务器会给没一个用户(浏览器)创建一个Session对象
  • 一个Session独占一个浏览器,只要浏览器没关闭,这个Session就存在
  • 用户登录之后,整个网站都可以访问
  • 应用保存用户信息

Session和Cookie的区别

  • Cookie是把用户的数据写给用户的浏览器,浏览器保存
  • Session是吧用户的数据写到用户独占的Session中,服务端保存
  • Session对象由服务器创建

创建使用Session

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 SessionDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();

        session.setAttribute("name", "鹿乃");
        String id = session.getId();

        if(session.isNew()){
            resp.getWriter().write("session创建成功,ID:"+id);
        }
        else{
            resp.getWriter().write("已经创建成功,ID:"+id);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

得到Session数据

String s = (String) session.getAttribute("name");

清除Session

主动清除

HttpSession session = req.getSession();

session.invalidate();

自动失效,xml配置

  <session-config>
<!--15分钟后session自动失效-->
    <session-timeout>15</session-timeout>
  </session-config>

猜你喜欢

转载自www.cnblogs.com/ijuysama/p/12789638.html