session(session的創建、設置、生命周期、特點、數據共享、seeion實現三天免登錄)


1、Session的獲取

(1)無參的方法:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        HttpSession httpSession=request.getSession();
        System.out.println(httpSession.getId());
    }

 

 請求中無Cookie,但是響應中存在Cookie:

 

 

 

 當再次訪問該Servlet的時候,請求中存在Cookie,響應中的Cookie已經沒有了:

 

 

 

以上為無參的方法獲取Session,如果沒有Session則創建一個,如果有則直接返回。

(2)有參的方法:

參數為false:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        HttpSession httpSession=request.getSession(false);
        System.out.println(httpSession.getId());
    }

如果有Session則直接返回。

沒有的話返回500錯誤:

 參數為true:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        HttpSession httpSession=request.getSession(true);
        System.out.println(httpSession.getId());
    }

此方法與不加參數等效。

 

 

 2、Session的有效期限:

 前三次訪問是連續訪問三次CookieServlet,可以看出,SESSIONID的值是不會發生變化的,但是當關閉了瀏覽器,第四次訪問CookieServlet時,SESSIONID發生了變化;第五次為更換了瀏覽器之后的結果,SESSIOID依舊會發生變化。

以下情況下Session需要重新建立:

(1)用戶關閉了瀏覽器。但是關閉了瀏覽器並不代表Seesion已經被銷毀了,因為Session保存在服務器內部。

(2)關閉了服務器。

(3)用戶沒有向服務器提出請求(超過30分鍾),過期后服務器自動刪除,從不操作服務端資源開始計時。

 

       可以修改(直接修改或在自己的web.xml中配置,將默認的時間覆蓋掉)。

 

3、Session的設置:

(1)時間:

   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        HttpSession httpSession=request.getSession(true);
        httpSession.setMaxInactiveInterval(10);//十秒后失效
        System.out.println(httpSession.getId());
    }

第一次訪問,成功返回SESSIONID。

 

 過十幾秒鍾后重新訪問發現SESSIONID的值已經改變了:

 這是因為第一個SESSIOID已經過期了,需要創建第二個。

(2)強制失效(手動銷毀):

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        HttpSession httpSession=request.getSession(true);
        httpSession.invalidate();
        System.out.println(httpSession.getId());
    }

 即執行invalidate()后可以將創建的SESSION立即結束。

 

4、session的特點:

(1)存儲在服務器端。

(2)依賴於Cookie,借助Cookie存儲JSESSIONID。

(3)存在有效期限。

 

5、session的數據共享

要體現出Session的數據共享,需要建立兩個Servlet:

第一個:建立Session,將值設置為Tom。

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String name="Tom"; HttpSession httpSession=request.getSession(true); httpSession.setAttribute("name",name); System.out.println(httpSession.getId()); }

第二個獲取Session:

   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession httpSession=request.getSession(); System.out.println(httpSession.getAttribute("name")); }

 也就是說對於不同的請求,都可以共享Session中的數據,他們的請求針對的是同一個Session,但是要保證Session沒有失效。即沒有關閉瀏覽器,沒有過期,Session中的數據存儲在服務器。

 

6、session的應用

(1)使用Cookie實現的登錄的不足:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=utf-8");//設置瀏覽器編碼格式
        Cookie[] cookies=request.getCookies();
        Connection con=null;
        login log= null;
        int successNum=0;
        try {
            con= C3p0Utils.getConnection();
            QueryRunner qr = new QueryRunner();
            String sql = "Select * from login";
            List<login> list = qr.query(con, sql, new BeanListHandler<login>((login.class)));

            if(cookies!=null) {//驗證數據庫中是否有與Cookie對應的用戶

                for (int i = 0; i < list.size(); i++) {
                    log= list.get(i);
                for (Cookie cookie : cookies) {
                        if((log.getAccount().equals(cookie.getName()))&&(log.getPassword().equals(cookie.getValue()))){
                           successNum++;
                        }
                }
                }
                if(successNum>=1){
                    response.getWriter().write("Successful login with Cookie!");
                }
                else{
                    request.getRequestDispatcher("page").forward(request,response);
                }

            }
            else{
                request.getRequestDispatcher("page").forward(request,response);//請求轉發
            }
        }
        catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html; charset=utf-8");//設置瀏覽器編碼格式
        response.getWriter().write("<html>"); response.getWriter().write("<head>"); response.getWriter().write("<title>"); response.getWriter().write("Login"); response.getWriter().write("</title>"); response.getWriter().write("</head>"); response.getWriter().write("<body bgcolor=\"aqua\">"); response.getWriter().write("<center>"); response.getWriter().write("<h3>");  response.getWriter().write("歡迎你"+request.getParameter("account")); response.getWriter().write("</h3>"); response.getWriter().write("</center>"); response.getWriter().write("</body>"); }

使用Cookie雖然實現了三天免登錄的基礎功能,但是,如果在用Cookie登錄成功后需要重定向(兩次請求,request對象不能攜帶數據)到另外一個Cookie時,request獲取的值在重定向的Servlet中已經不再起作用了,訪問的結果只能是空值。

 

(2)使用Session的請求共享功能,實現在不同的Servlet跳轉過程中依舊能夠通過request獲得用戶信息。

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8");//設置瀏覽器編碼格式 Cookie[] cookies=request.getCookies(); Connection con=null; login log= null; int successNum=0; try { con= C3p0Utils.getConnection(); QueryRunner qr = new QueryRunner(); String sql = "Select * from login"; List<login> list = qr.query(con, sql, new BeanListHandler<login>((login.class))); if(cookies!=null) {//驗證數據庫中是否有與Cookie對應的用戶 for (int i = 0; i < list.size(); i++) { log= list.get(i); for (Cookie cookie : cookies) { if((log.getAccount().equals(cookie.getName()))&&(log.getPassword().equals(cookie.getValue()))){ HttpSession httpSession=request.getSession(); httpSession.setAttribute("login",log); successNum++; } } } if(successNum>=1){ response.sendRedirect("/Servlet_login_war_exploded/main");//重定向  } else{ request.getRequestDispatcher("page").forward(request,response); } } else{ request.getRequestDispatcher("page").forward(request,response);//請求轉發  } } catch (SQLException e) { throw new RuntimeException(e); } }

在通過Cookie登錄成功后,創建了Session,對Session進行了賦值,而在重定向到MainServlet后,可以從Session中獲取值。雖然在不同的Servlet中,是不同的請求,但是依舊能夠通過Session獲取值。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     login log= (login) request.getSession().getAttribute("login"); response.setContentType("text/html; charset=utf-8");//設置瀏覽器編碼格式 response.getWriter().write("<html>"); response.getWriter().write("<head>"); response.getWriter().write("<title>"); response.getWriter().write("Login"); response.getWriter().write("</title>"); response.getWriter().write("</head>"); response.getWriter().write("<body bgcolor=\"aqua\">"); response.getWriter().write("<center>"); response.getWriter().write("<h3>");  response.getWriter().write("歡迎你"+log.getAccount()); response.getWriter().write("</h3>"); response.getWriter().write("</center>"); response.getWriter().write("</body>"); }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM