继续学习servlet,这里开始学习servlet session的用法。
先看API 中对HttpSession接口的定义:
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.
The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user. A session usually corresponds to one user, who may visit a site many times. The server can maintain a session in many ways such as using cookies or rewriting URLs.
本人英语水平欠佳,翻译不了这段话,但是大体意思还是明白的:session保存了用户的信息,可以在不同的页面间共享用户信息。维持会话还可以通过cookies或者重定向的方法,恩,先学习session,后面再介绍cookies。
对于session,韩顺平老师有个形象的介绍:某个浏览器访问了servlet服务器,服务器便为该浏览器开辟出一块单独内存,在这块内存中保留浏览器的信息,这就是session,可以把session看做是一个二维表,表中以属性:属性值保存用户数据。听了这个介绍,概念上便清晰了许多,下面看session的具体使用。
这里模拟用户登录之后,将用户名和密码保存在session中作为学习的例子:
public void doGet(HttpServletRequest req,HttpServletResponse res){
try{
//接收用户名和密码
String u = req.getParameter("username");
String p = req.getParameter("pass");
//1得到session
HttpSession hs = req.getSession(true);
//2修改session的存在时间
hs.setMaxInactiveInterval(2000);
hs.setAttribute("user",u);
hs.setAttribute("pass",p);
}catch(Exception ex)
{
ex.printStackTrace();
}
}
当然这里省略了用户验证的步骤,首先通过HttpServletRequest对象的getSession()方法获得HttpSession对象,然后将属性和属性值通过serAttribute()方法写到session中,session缺省的存在时间是半小时,可以通过setMaxInacticeInterval()来手动设置存在时间。
再看一下session的读取:
//得到session
HttpSession hs = req.getSession(true);
String user = (String)hs.getAttribute("user")
String pass = (String)hs.getAttribute("pass");
通过getAttribute()就可以获得相应属性的值了,返回值为Object类型。还有其他方法,详见参考手册。