HttpSession

The HttpSession object represents a user session. A user session contains information about the user across multiple HTTP requests.

When a user enters your site for the first time, the user is given a unique ID to identify his session by. This ID is typically stored in a cookie or in a request parameter.

Here is how you access the session object:

protected void doPost(HttpServletRequest request,
    HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
}

You can store values in the session object, and retrieve them later. First, let’s see how you can store values in the session object:

session.setAttribute("userName", "theUserName");

This code sets an attribute named “userName“, with the value “theUserName“.

To read the value again, you do this:

String userName = (String) session.getAttribute("userName");

Values stored in the session object are stored in the memory of the servlet container.

Sessions and Clusters

If you have an architecture with 2 web servers in a cluster, keep in mind that values stored in the session object of one server, may not be available in the session object on the other server. So, if a user’s requests are divided evenly between the two servers, sometimes session values may be missing.

The solution to this problem would be one of:

  • Do not use session attributes.
  • Use a session database, into which session attributes are written, and from which it is read.
  • Use sticky session, where a user is always sent to the same server, throughout the whole session.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值