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:常见方法
- 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.
- removeAttribute(String name):移除一个特定的属性
- isNew() :Returns
true
if the client does not yet know about the session or if the client chooses not to join the session. - invalidate():丢弃整个会话信息。
方法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所指的客户端为访问它的浏览器。并非指计算机。