您的位置:首页 > 其它

Servlet 第六课: Session的使用

2014-08-07 18:04 267 查看
课程目标:

通过这节课,我们能够学会加入session,学会调用session,以及大概懂得session存在的情况。

课程具体:

1.Session仅仅是存在于浏览器。比方我们打开浏览器获得我们所须要的session,我们在同一个浏览器再打开,我们所须要的这个session是还存在的。

可是假设我们换用其它的浏览器或者直接关闭浏览器,那么这个session就会过期。

2.Session

–Session 是用来跟踪用户当前状态的一种机制,是针对浏览器和server的一对一关系。

–Session 的一般使用方法是,在用户登录时将用户的登录信息保存到session中,以便以后使用。

3.Session 接口HttpSession

通常我们仅仅使用HttpSession接口,接口的实现由web容器来完毕

–能够从HttpServletRequest中获得HttpSession

request.getSession();

–将信息保存在HttpSession中

session.setAttribute(“UserSession”,obj);【特别注意:这里是能够直接存放obj对象的,打个例如我们这里能够直接存放一个user对象】

–从HttpSession中获得信息

session.getAttribute(“UserSession”);

–使HttpSession失效

session.invalidate();

4.实例解说:

事实上这个session的使用我认为和cookie的使用基本差点儿相同。

设置Session Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.setAttribute("session_name", "session_value");
}

获得Session Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String value = (String)session.getAttribute("session_name");
System.out.println(value);
}

[/code]
5. Session 实例,登录Session

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//为了获取前台传过来的数据:username and password
String username = request.getParameter("username");
String password = request.getParameter("password");
//调用dao的实现逻辑:比方要验证用户账号和密码是否正确
//假设正确,再通过username和password查询出全部须要的信息,然后再封装成一个user对象
UserDao dao = new UserDaoImpl();
User u = dao.login(username, password);

if(u!=null){
//推断,假设用户存在,就封装一个user对象,发给jsp
HttpSession session = request.getSession();
session.setAttribute("user", u);
request.getRequestDispatcher("welcome.jsp").forward(request, response);
}else{
//推断,假设用户不存在,那么直接跳转到错误页面
request.getRequestDispatcher("error.html").forward(request, response);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: