Session

1:什么是Session

Session是存储在服务器端保存客户端信息的一个对象。下面是原始API对Session的定义:Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user。

 用户的多个请求页面之间可以通过Session对象实现信息共享。

2:怎么创建一个Session

  因为HttpSession是一个接口所以不能直接创建,我们可以HttpServletRequest的getSession()方法得到Session。  HttpSession session = request.getSession();

3:常见方法

  1.   setAttribute(String name,Object value)/getAttriute(String name):存储或取得信息。如果setAttribute(String name,Object value)name相同,那么会覆盖之前的value.             比如:session.setAttribute("name","value");                   session.setAttribute("name","newValue");那么name所对应的值将变成newValue   即session.getAttribute("name")返回newValue.
  2.   removeAttribute(String name):移除一个特定的属性
  3.   isNew() :Returns true if the client does not yet know about the session or if the client chooses not to join the session.
  4. invalidate():丢弃整个会话信息。
4:设置会话过期时间

  方法1:配置Tomcat的web.xml文件,存放在: Tomcat目录\conf\web.xml。修改session-timeout,以分钟为单位

<session-config>
        <session-timeout>30</session-timeout>
    </session-config>

       方法2:通过调用HttpSession的setMaxInactiveInterval(int interval)方法,以秒为单位。

5:Session是存储在服务器端保存客户端信息的一个对象。那么同一主机上的不同浏览器算同一个客户端吗?

   创建一个Servlet,代码如下:

    protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 如果不存在 session 会话,则创建一个 session 对象
HttpSession session = request.getSession(true);
Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
if (session.isNew()) {
session.setAttribute(visitCountKey, visitCount);
} else {
visitCount = (Integer) session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
}
session.setAttribute(visitCountKey, visitCount);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("这是第: "+session.getAttribute("visitCount")+" 次请求");
}

   当用同一个浏览器访问时,实现了共享Session。

   但用不同浏览器访问时(本人使用的 IE和Google Chrome),他们各自记录自己的访问次数。

所以通过这次实验也明确认识了Web所指的客户端为访问它的浏览器。并非指计算机。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值