课程目标:
通过这节课,我们可以学会添加session,学会调用session,以及大概懂得session存在的情况。
课程详细:
1.Session只是存在于浏览器。比如我们打开浏览器获得我们所需要的session,我们在同一个浏览器再打开,我们所需要的这个session是还存在的。
但是如果我们换用其他的浏览器或者直接关闭浏览器,那么这个session就会过期。
2.Session
–Session 是用来跟踪用户当前状态的一种机制,是针对浏览器和服务器的一对一关系。
–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的使用基本差不多。
5. Session 实例,登录Session设置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); }
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);
}
}