HttpSession

HttpSession

HttpSession 服务端技术
HttpSession原理
当用户端第一次访问Servlet时 服务端会给该用户创建
一个独立Session 并且生成一个SessionID
这个SessionID在响应浏览器的时候 会被装进cookie中
从而被保存到浏览器中
当用户再一次访问 Servlet的时候
请求中会携带着 cookie中的 SessionID 去访问
服务器会根据这个SessionID  去查看是否有对应的 Session对象
有 就拿出来用
没有 就创建一个Session(相当于第一次访问)

Session域 只要会话不结束 就会存在
但是 Session有默认的存活时间 30分钟

以下面两个demo为例  具体看一下Session对象的作用

// 获取Session对象 并保存数据
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);
    }
    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");
        // 响应到网页上
        response.getWriter().write(username + "   " + session.getId()); 
    }

    public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值