天天看點

重溫Servlet學習筆記--session對象

  session的類型是屬于HttpSession,HttpSession是由javaWeb提供的,用來會話跟蹤的類.session是伺服器端對象,儲存在伺服器端.

  •   HttpSession是servlet三大域對象之一,其他兩個是request和application(servletContext),是以它也有setAttribute(),getAttribute(),等方法.
  •   HttpSession的會話範圍是某使用者從首次通路伺服器開始,到該使用者關閉浏覽器結束,session對象會存活在這中間的整個過程,  伺服器會為每個用戶端建立一個session對象,session就好像是客戶在伺服器端的賬戶,他被伺服器儲存在一個Map裡,這個Map被稱為session緩存.
  • session的實作原理

   session底層是依賴Cookie的!我們來了解一下session的原理吧!

    當我首次去銀行時,因為還沒有賬号,是以需要開一個賬号,我獲得的是銀行卡,而銀行這邊的資料庫中留下了我的賬号,我的錢是儲存在銀行的賬号中,而我帶走的是我的卡号。當我再次去銀行時,隻需要帶上我的卡,而無需再次開一個賬号了。隻要帶上我的卡,那麼我在銀行操作的一定是我的賬号!

      當首次使用session時,伺服器端要建立session,session是儲存在伺服器端,而給用戶端的session的id(一個cookie中儲存了sessionId)。用戶端帶走的是sessionId,而資料是儲存在session中。當用戶端再次通路伺服器時,在請求中會帶上sessionId,而伺服器會通過sessionId找到對應的session,而無需再建立新的session。

     下面寫一個簡單的案例,加深一下對session和cookie的了解,我們要實作一個簡單的登入功能,登入成功時會将使用者名儲存到一個session中,同時也儲存到一個cookie中,然後會跳轉到成功頁面,但使用者直接輸入url通路成功頁面時,需要驗證使用者是否已登入(用session),如果沒有登陸則跳轉回登入頁面,當浏覽器關閉再打開通路登入頁面時,自動顯示上一次的通路登入使用者名(用cookie):

建立一個jsp,命名為login.jsp(head标簽内容已省略):

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  
  <body>
  <%
          String username="";
          Cookie[] cookie=request.getCookies();
          if(cookie!=null){
              for(Cookie c:cookie){
                  if("username".equals(c.getName())){
                      username=c.getValue();
                  }
              }
          }
  %>
  <form  action="<c:url value='/LoginServlet'/>" method="post">  
  <label style="font-color:red;">${errorLogin }</label><br>
   使用者名:<input type="text" name="username" value="<%=username%>"/><br>
   密碼:<input type="password" name="password"/><br>
   <input type="submit" value="登入"/>
  </form>
  
  </body>
</html>      

建立一個servlet,命名為LoginServlet,用來處理登入邏輯,并完整各個功能(隻提供關鍵代碼):

public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=utf-8");
    String username=request.getParameter("username");
    String password=request.getParameter("password");
    if(username.equals("wang")&&password.equals("123")){
        HttpSession session = request.getSession();
        session.setAttribute("username", username);
        session.setAttribute("password", password);
        Cookie cookie=new Cookie("username",username);
        cookie.setMaxAge(60*60*24*7);
        response.addCookie(cookie);
        response.sendRedirect("/test/sessionDemo1/succ1.jsp");
    }else{
        request.setAttribute("errorLogin", "使用者名或密碼錯誤");
        request.getRequestDispatcher("/sessionDemo1/login.jsp").forward(request, response);
    }
    }      

最後建立一個登陸成功時的jsp頁面,命名為succ1.jsp(隻提供body部分代碼):

<body>
    <%
        String username=(String)session.getAttribute("username");
        String password=(String)session.getAttribute("password");
        if(username==null){
            request.setAttribute("errorLogin", "您還沒有登入,請先登入");
            request.getRequestDispatcher("/sessionDemo1/login.jsp").forward(request, response);
            return;
        }
            
    %>
    登陸成功,你好${username }
  </body>      
  • HttpSession的其他方法:
  1. String getId():擷取sessionId
  2. int getMaxInactiveInterval();擷取session的最大不活動時間,預設為30分鐘,如果session在30分鐘内沒有被使用,Tomcat就會在session池中移除這個session對象
  3. void invalidate();讓session失效,使用者登出時,可以調用該方法
  • web.xml中配置session的最大不活動時間:
    <session-config>
          <session-timeout>20</session-timeout>
      </session-config>      
    session最常用的東西就是作為域對象,傳遞參數,也是最重要的,其他的知識點在某些地方也很重要,要好好了解.