第74節:Java中的Cookie和Session

達叔小生發表於2019-01-24

標題圖

第74節:第74節:Java中的Cookie和Session

ServletContext:

什麼是ServletContext,有什麼用哦,怎麼用呢?

啟動伺服器後,會給每個應用程式建立一個ServletContext,並且這個ServletContext物件只有一個。可以用於獲取全域性引數,工程下的資源,和存取資料,共享資料。

例子,如何獲取全域性引數,如何獲取工程下的資源,如何進行存取資料,用例子程式碼進行展示。

getServletContext().getInitParams();getServletConfig().getInitParams();

getServletContext().getRealPath()
getServletContext().getReasourceAsStream()

InputStream is = getClass().getClassLoader().getReasourceAsStream();

相對路徑和絕對路徑

getServletContext().setAttribute()

getServletContext().getAttribute()

獲取登入成功次數

HttpServletRequest:

請求物件,用於封裝客戶端提交過來的資料或者資訊。
可以獲取頭資訊,提交過來的資料:
`request.getParameter(“name”); // dashucoding url連線拼接

中文亂碼情況

HttpServletResponse:

響應物件,伺服器要返回給客戶端的資料

跳轉頁面:
response.setStatus(302);

response.setHeader("Location","success.html");

檔案下載:輸出流和輸入流的對接

下載中文名字的資源:

效果

效果

// index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

    預設servlet去下載<br>
    <a href="download/aa.jpg">aa.jpg</a><br>
    <a href="download/bb.txt">bb.txt</a><br>
    <a href="download/cc.rar">cc.rar</a><br>

    <br>手動下載<br>
    <a href="Demo01?filename=aa.jpg">aa.jpg</a><br>
    <a href="Demo01?filename=bb.txt">bb.txt</a><br>
    <a href="Demo01?filename=cc.rar">cc.rar</a><br>
    <a href="Demo01?filename=達叔.png">達叔.png</a><br>
</body>
</html>
// Demo01.java
package com.dashucoding.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Demo01
 */
public class Demo01 extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        // 獲取要下載的檔名字
        String fileName = request.getParameter("filename");
        // 獲取這個檔案在tomcat裡面的絕對路徑地址
        String path = getServletContext().getRealPath("download/"+fileName);
        
        // 用於使用者下載
        response.setHeader("Content-Disposition", "attachment; filename="+fileName);
        
        // 轉化成輸入流
        InputStream is = new FileInputStream(path);
        OutputStream os = response.getOutputStream();
        
        int len = 0;
        byte[] buffer = new byte[1024];
        while( (len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        
        os.close();
        is.close();
        
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

瀏覽器

// Demo01.java
package com.dashucoding.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Demo01
 */
public class Demo01 extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        // 獲取要下載的檔名字
        String fileName = request.getParameter("filename");
        
        // get請求有中文
        //byte[] bytes = fileName.getBytes("ISO-8859-1");
        //new String(bytes, "UTF-8");
        fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8");
        System.out.println("fileName="+fileName);
        
        // 獲取這個檔案在tomcat裡面的絕對路徑地址
        String path = getServletContext().getRealPath("download/"+fileName);
        
        // 對中文的名字進行編碼處理
        // 獲取來訪客戶端的型別
        String clientType = request.getHeader("User-Agent");
        
        if (clientType.contains("Firefox")) {
            fileName = DownLoadUtil.base64EncodeFileName(fileName);
        }else {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        }
        
        // 用於使用者下載
        response.setHeader("Content-Disposition", "attachment; filename="+fileName);
        
        // 轉化成輸入流
        InputStream is = new FileInputStream(path);
        OutputStream os = response.getOutputStream();
        
        int len = 0;
        byte[] buffer = new byte[1024];
        while( (len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        
        os.close();
        is.close();
        
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
// DownLoadUtil
package com.dashucoding.servlet;

import java.io.UnsupportedEncodingException;

import sun.misc.BASE64Encoder;

public class DownLoadUtil {
    public static String base64EncodeFileName(String fileName) {
        BASE64Encoder base64Encoder = new BASE64Encoder();
        try {
            return "=?UTF-8?B?"
                    + new String(base64Encoder.encode(fileName
                            .getBytes("UTF-8"))) + "?=";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}

效果

登入

效果

// LoginServlet
package com.dashucoding.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        // public void setContextType(String type)
        // 設定將傳送到客戶端的響應的內容型別,如果該響應尚未提交,給定內容型別可能包含字元編碼規範,例如
        // text/html;charseet=UTF-8,如果在呼叫 getWriter之前呼叫此方法,則只根據給定內容型別設定響應的字元編碼
        
        response.setContentType("text/html;charset=utf-8");
        
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        
        if("admin".equals(userName) && "123".equals(password)) {
            response.getWriter().write("登入成功");
        }else {
            response.getWriter().write("登入失敗");
        }
        
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
// web
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>RequestRedirctionDemo</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>LoginServlet</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.dashucoding.servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>
</web-app>
// login
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

    <form action="login">
        賬號: <input type="text"  name="username"/><br>
        密碼: <input type="text"  name="password"/><br>
        <input type="submit"  value="登入"/><br>
    </form>
</body>
</html>

效果

效果

效果

// LoginServlet
package com.dashucoding.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        // public void setContextType(String type)
        // 設定將傳送到客戶端的響應的內容型別,如果該響應尚未提交,給定內容型別可能包含字元編碼規範,例如
        // text/html;charseet=UTF-8,如果在呼叫 getWriter之前呼叫此方法,則只根據給定內容型別設定響應的字元編碼
        
        response.setContentType("text/html;charset=utf-8");
        
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        
        if("admin".equals(userName) && "123".equals(password)) {
            // response.getWriter().write("登入成功");
            response.setStatus(302);
            response.setHeader("Location", "login_success.html");
        }else {
            response.getWriter().write("登入失敗");
        }
        
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

效果

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>登入成功!!!</h1>
</body>
</html>

效果

重定向

package com.dashucoding.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        // public void setContextType(String type)
        // 設定將傳送到客戶端的響應的內容型別,如果該響應尚未提交,給定內容型別可能包含字元編碼規範,例如
        // text/html;charseet=UTF-8,如果在呼叫 getWriter之前呼叫此方法,則只根據給定內容型別設定響應的字元編碼
        
        response.setContentType("text/html;charset=utf-8");
        
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        
        if("admin".equals(userName) && "123".equals(password)) {
            // response.getWriter().write("登入成功");
            /*response.setStatus(302);
            response.setHeader("Location", "login_success.html");*/
            
            // 重定向寫法,重新定位方向
            // response.sendRedirect("login_success.html");
            
            // 請求轉發的寫法
            request.getRequestDispatcher("login_success.html").forward(request, response);
            
        }else {
            response.getWriter().write("登入失敗");
        }
        
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

用於自動登入,瀏覽記錄等,是伺服器給客戶端的.

Cookie cookie = new Cookie("a","b");
// 響應
response.addCookie(cookie);

獲取Cookie

package com.dashucoding.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Demo01
 */
public class Demo01 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        //Cookie的簡單使用。
        
        //cookie 傳送給客戶端,並且儲存在客戶端上的一份小資料
        
        response.setContentType("text/html;charset=utf-8");
        
        //傳送cookie給客戶端
        Cookie cookie = new Cookie("aa", "bb");
        //給響應,新增一個cookie
        response.addCookie(cookie);
        response.getWriter().write("請求成功了...");
        
        
        
        //獲取客戶端帶過來的cookie
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for (Cookie c : cookies) {
                String cookieName = c.getName();
                String cookieValue = c.getValue();
                System.out.println(cookieName + " = "+ cookieValue);
            }
        }
        
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }


}

Cookie是一份小資料,是伺服器給客戶端,儲存在客戶端上的一份小資料.

http請求是無狀態的.

在響應的時候新增Cookie

Cookie cookie = new Cookie("name", "value");
// 新增cookie
response.addCookie(cookie);

在客戶端資訊裡,響應頭中多了Set-Cookie

獲取客戶端帶來的Cookie

Cookie[] cookies = request.getCookies();
if(cookies != null){
 for(Cookie c : cookies){
  String cookieName = c.getName();
  String cookieValue = c.getValue();
  System.out.println(cookieName + " = " + cookieValue);
 }
}

cookie過期

public int getMaxAge()
返回以秒為單位指定的cookie的最大生存時間.

public void setMaxAge(int expiry)
設定cookie的最大生存時間,以秒為單位.

如何顯示上次登入時間

可以進行判斷賬號密碼,如果上次有登入過,那麼顯示上次的登入時間.這裡分兩種情況,獲取帶過來的cookie進行判斷,第一種是沒有cookie的,第一次登入,輸出登入成功或者失敗,然後給客戶端新增cookie,new Cookie(),第二種的登入過的,還是要輸出登入成功或者是失敗,獲取以前的cookie.時間戳要重置怎麼理解?

package com.dashucoding.servlet;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dashucoding.util.CookieUtil;

/**
 * Servlet implementation class Demo03
 */
public class Demo03 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        response.setContentType("text/html;charset=utf-8");
        
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        
        if("admin".equals(userName) && "123".equals(password)){
            //獲取cookie last-name --- >
            Cookie [] cookies = request.getCookies();
            
            //從陣列裡面找出我們想要的cookie
            Cookie cookie = CookieUtil.findCookie(cookies, "last");
            
            //是第一次登入,沒有cookie
            if(cookie == null){
                
                Cookie c = new Cookie("last", System.currentTimeMillis()+"");
                c.setMaxAge(60*60); //一個小時
                response.addCookie(c);
                
                response.getWriter().write("歡迎您, "+userName);
                
            }else{
                //1. 去以前的cookie第二次登入,有cookie
                long lastVisitTime = Long.parseLong(cookie.getValue());
                
                //2. 輸出到介面,
                response.getWriter().write("歡迎您, "+userName +",上次來訪時間是:"+new Date(lastVisitTime));
                
                
                //3. 重置登入的時間
                cookie.setValue(System.currentTimeMillis()+"");
                response.addCookie(cookie);
            }
        }else{
            response.getWriter().write("登陸失敗 ");
        }
    
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

如何顯示商品瀏覽記錄

獲取提交過來的id,把id放入到cookie裡,跳轉介面.

servlet?id=1;
servlet?id=2;
獲取cookie 1
1#2
setValue("1#2");

jsp

效果

效果

// index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <br>---------1------------<br>
 <%! int a = 123; %>
 <br>---------2------------<br>
 <% int b = 123456; %>
 <br>---------3------------<br>
 <%=a %><br>
 <%=b %>
</body>
</html>

瀏覽記錄

package com.dashucoding.util;

import javax.servlet.http.Cookie;

public class CookieUtil {
    /**
     * 從一個cookie陣列中找到具體我們想要的cookie物件
     * @param cookies
     * @param name
     * @return
     */
    public static Cookie findCookie(Cookie[] cookies , String name){
        if(cookies != null){
            for (Cookie cookie : cookies) {
                if(name.equals(cookie.getName())){
                    return cookie;
                }
            }
        }
        return null;
    }
}
                <!-- 顯示瀏覽記錄 -->
                <%
                Cookie[] cookies = request.getCookies();
                Cookie cookie = CookieUtil.findCookie(cookies, "history");
                 // 如果cookie是空,表明沒有瀏覽商品
                 if(cookie == null){
                %>
                 <h2> 您還沒有瀏覽任何商品! </h2>
                <%
                }else{
                    // 不是空,表明有瀏覽記錄
                    String[] ids = cookie.getValue().split("#");
                    for(String id : ids){
                %>
                <li style="width: 150px;height: 216;text-align: center;"><img src="products/1/cs1000<%=id %>.jpg" width="130px" height="130px" /></li>
                <%
                    }
                }
                %>
package com.dashucoding.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dashucoding.util.CookieUtil;

public class ProductInfoServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Cookie[] cookies = request.getCookies();
        Cookie cookie = CookieUtil.findCookie(cookies, "history");
        if (cookie==null) {
            Cookie cook = new Cookie("history", id);
            cook.setMaxAge(60*60*24*7);
            response.addCookie(cook);
        }else{
            String id2 = cookie.getValue();
            cookie.setValue(id+"#"+id2);
            cookie.setMaxAge(60*60*24*7);
            response.addCookie(cookie);
        }
        response.sendRedirect("product_info.htm");
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

清除瀏覽記錄

清除cookie

package com.dashucoding.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ClearHistory
 */
public class ClearHistory extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        // 清除cookie
        Cookie c = new Cookie("history", "");
        c.setMaxAge(0);
//      c.setPath("/demo1");
        response.addCookie(c);
        response.sendRedirect("product_list.jsp");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

獲取cookie,新增cookie

request.getCookie();
response.addCookie();

Cookie分類

cookie.setMaxAge(0); // 刪除
cookie.setMaxAge(100); // 100秒

Cloneable

建立一個cookie,cookieservlet傳送到web瀏覽器中的少量資訊,這些資訊是由瀏覽器儲存,然後傳送回到伺服器中.

cookie的值是唯一標識客戶端的,可以用於cookie會話管理.一個cookie擁有一個名,值,可以有一些可選屬性.但又cookie也存在一些問題.瀏覽器支援每個web伺服器又20個cookie,共有300個cookie,每個限制在4KB.

安全隱患,大小與個數限制.

Session

會話,Session是基於Cookie的一種會話機制.Cookie是伺服器返回一部分小資料在客戶端,存放在客戶端上.

Session是把資料存放在服務端.

interface httpsession

public interface httpSession

常用的方法

package com.dashucoding.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class Demo01
 */
public class Demo01 extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        HttpSession session = request.getSession();
        // 得到會話ID
        session.getId();
        // 存值
        session.setAttribute(name, value);
        // 取值
        session.getAttribute(name);
        // 移植
        session.removeAttribute(name);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

效果

效果

// web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>SessionDemo02</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>LoginServlet</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.dashucoding.servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>
</web-app>
// LoginServlet
package com.dashucoding.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("收到請求了");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
// login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <form action="login">
        賬號: <input type="text"  name="username"/><br>
        密碼: <input type="text"  name="password"/><br>
        <input type="submit"  value="登入"/><br>
    </form>
</body>
</html>

session建立與銷燬

建立 request.getSession();
銷燬 Redis session 存放在伺服器記憶體中的資料
session關閉伺服器銷燬
session會話時間過期
// 可以改的 confweb.xml 有效期30分鐘
<session-config>
 <session-timeout>30</session-timeout>
</session-config>
package com.dashucoding.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        
        response.setContentType("text/html;charset=utf-8");
        
        String sessionid = request.getSession().getId();
        System.out.println("sessionid="+sessionid);
        // cookid id -> sessionid
        response.getWriter().write("收到請求了");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

session分析

商品列表新增商品,點選商品新增到購物車,到servlet.

獲取點選商品標識id,儲存到購物車,跳轉介面.

判斷購物車是否有商品,有數量加1,沒有數量等於1.

購物車

效果

效果

效果

package com.dashucoding.servlet;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CarServlet
 */
public class CarServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        
        response.setContentType("text/html;charset=utf-8");
        // 獲取新增到購物車的商品id
        int id = Integer.parseInt(request.getParameter("id"));
        // cat dog big pig
        String [] names = {"cat","dog","big","pig"};
        // 取到id對應商品
        
        String name = names[id];
        
        // 獲取購物車存放東西的session
        // 把一個map 物件存放到session裡面去,保證只有一次
        
        Map<String, Integer> map = (Map<String, Integer>) request.getSession().getAttribute("cat");
        
        if(map == null) {
            // value -> map
            
            map = new LinkedHashMap<String, Integer>();
            
            request.getSession().setAttribute("cat", map);
        }
        
        // 判斷購物車裡有沒有該商品
        if(map.containsKey(name)) {
            // 在原來基礎上 +1
            map.put(name, map.get(name)+1);
        }else {
            map.put(name, 1);
        }
        
        response.getWriter().write("<a href=`product_list.jsp`><h2>繼續購物</h2></a>");
        response.getWriter().write("<a href=`cart.jsp`><h2>去購物車結算</h2></a>");
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 <a href="CarServlet?id=0"><h2>cat</h2></a><br>
 <a href="CarServlet?id=1"><h2>dog</h2></a><br>
 <a href="CarServlet?id=2"><h2>big</h2></a><br>
 <a href="CarServlet?id=3"><h2>pig</h2></a><br>
</body>
</html>

效果

效果

// cart.jsp
<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 您的購物車商品如下:
 <%
  // 獲取到map
  Map<String,Integer> map = (Map<String,Integer>)session.getAttribute("cat");
  // 遍歷
  if(map != null){
      for(String key : map.keySet()){
          int value = map.get(key);
          // key:商品名稱 value:商品名稱
          // <h3>名稱: 數量: </h3>
  %>
        <h3>名稱: <%=key %> 數量: <%=value %></h3><br>
  <%
      }
  }
  %>
</body>
</html>

效果

package com.dashucoding.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class ClearCartServlet
 */
public class ClearCartServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        
        HttpSession session = request.getSession();
        
        // cat購物車
        session.removeAttribute("cat");
        response.sendRedirect("cart.jsp");
        
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 您的購物車商品如下:
 <%
  // 獲取到map
  Map<String,Integer> map = (Map<String,Integer>)session.getAttribute("cat");
  // 遍歷
  if(map != null){
      for(String key : map.keySet()){
          int value = map.get(key);
          // key:商品名稱 value:商品名稱
          // <h3>名稱: 數量: </h3>
  %>
        <h3>名稱: <%=key %> 數量: <%=value %></h3><br>
  <%
      }
  }
  %>
  <a href="ClearCartServlet"><h4>清空購物車</h4></a>
</body>
</html>

效果

public void invalidate()
使用,會話無效,取消對任何繫結到它的物件.
// 強制幹掉會話
// session.invalidate();

小結

cookie和session

Cookie
獲取上一次訪問時間,獲取瀏覽記錄,資料存放在客戶端

Session
會話技術,資料存放在服務端

setAttribute 存放資料
getAttribute 取資料
removeAttribute 移除
getSessionId() 獲取會話id
invalidate() 讓會話失效
response.addCookie(new Cookie())
request.getSession 建立

如果看了覺得不錯

點贊!轉發!

達叔小生:往後餘生,唯獨有你
You and me, we are family !
90後帥氣小夥,良好的開發習慣;獨立思考的能力;主動並且善於溝通
簡書部落格: 達叔小生
https://www.jianshu.com/u/c785ece603d1

結語

  • 下面我將繼續對 其他知識 深入講解 ,有興趣可以繼續關注
  • 小禮物走一走 or 點贊

相關文章