Java中Session域对象

Session域对象

    /*
 * HttpSession 服务端的技术
 * 服务器会为每一个用户 创建一个独立的HttpSession
 * HttpSession原理
 * 当用户第一次访问Servlet时 服务器端会给该用户创建一个独立的session
 * 并且生成一个SessionID
 * 这个SessionID在响应浏览器的时候 会被装进cookie中
 * 从而被保存到浏览器中
 * 当用户再一次访问 Servlet的时候 
 * 请求中会携带着 cookie中的SessionID去访问
 * 服务器会根据这个SessionID去查看是否有对应的Session对象
 * 有就拿出来使用
 * 没有就当第一次访问 重新创建一个Session(相当于用户第一次访问)
 * 
 * 域的范围
 * context域 >Session域 >request域
 * Session域 只要会话不结束 就会存在
 * 但是 Session有默认的存活时间 30分钟
 * 
 * 模拟购物功能
 * 大概需要几个页面来完成 --- 需要几个Servlet类
 * 需要:
 * 三个Servlet类
 * session中 保存什么数据合适 添加一个保存数的容器
 * 书类 id bookname
 * 模拟假数据 逻辑和功能跑通了 再连接数据库
 * map集合 HashMap<String,Book>
 * 方法: 根据ID 获取对应的书
 * 
 */
public class Demo01 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        // 获取参数
        String username = request.getParameter("username");
        //获取session对象
        HttpSession session = request.getSession();
        // 保存数据
        session.setAttribute("username", username);
        System.out.println(session.getId());
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}
    /*
 * 测试获取session域中的数据
 */
public class Demo02 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        // 获取session域中的数据
        HttpSession session = request.getSession();
        String username = (String)session.getAttribute("username");
        System.out.println(session.getId());
        // 响应到网页上
        response.getWriter().write(username+session.getId());


    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值