Servlet 第六課: Session的使用,servletsession
課程目標:
通過這節課,我們可以學會添加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的使用基本差不多。
設定Session Servletprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); session.setAttribute("session_name", "session_value"); } 獲得Session Servletprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {HttpSession session = request.getSession(); String value = (String)session.getAttribute("session_name");System.out.println(value);}
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對象,發給jspHttpSession session = request.getSession();session.setAttribute("user", u);request.getRequestDispatcher("welcome.jsp").forward(request, response);}else{//判斷,如果使用者不存在,那麼直接跳轉到錯誤頁面request.getRequestDispatcher("error.html").forward(request, response);}}
怎在servlet中使用session????
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//通過request得到session
request.getSession().setAttribute(arg0, arg1);
}
session在servlet中的使用
servlet 中你先擷取session :request.getSession().getAttribute("你的session名稱")