Cookie和Session
會話
會話:用戶打開一個瀏覽器,點擊了很多超鏈接,訪問多個web資源,關閉瀏覽器,這個過程可以稱之爲會話;
有狀態會話:一個同學來過教室,下次再來教室,我們會知道這個同學,曾經來過,稱之爲有狀態會話;
一個網站,怎麼證明你來過?
客戶端 服務端
- 服務端給客戶端一個 信件,客戶端下次訪問服務端帶上信件就可以了; cookie
- 服務器登記你來過了,下次你來的時候我來匹配你; seesion
保存會話的兩種技術
cookie
- 客戶端技術 (響應,請求)
session
- 服務器技術,利用這個技術,可以保存用戶的會話信息? 我們可以把信息或者數據放在Session中!
常見場景:網站登錄之後,你下次不用再登錄了,第二次訪問直接就上去了!
Cookie
- 從請求中拿到cookie信息
- 服務器響應給客戶端cookie
實現顯示上次訪問時間
public class CookieServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解決中文亂碼問題
resp.setContentType("text/html");
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
//獲取cookie
Cookie[] cookies = req.getCookies();
PrintWriter out = resp.getWriter();
if (cookies!=null){
out.print("你上一次訪問的時間是:");
for (int i = 0; i <cookies.length ; i++) {
Cookie cookie = cookies[i];
//獲取cookie的鍵
if (cookie.getName().equals("timing")){
//獲取cookie的值
long lasteLoginTime = Long.parseLong(cookie.getValue());
Date date = new Date(lasteLoginTime);
out.print(date.toLocaleString());
}
}
}else {
out.print("這是你第一次訪問");
}
//創建一個cookie存放上次訪問的時間
Cookie cookie = new Cookie("timing",System.currentTimeMillis()+"");
//設置cookie存活時間爲1天
cookie.setMaxAge(24*60*60);
//添加cookie
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
第一次訪問
第二次訪問
有的瀏覽器第一次就會有一些cookie,這裏用的是Microsoft edge。
Session
什麼是Session:
- 服務器會給每一個用戶(瀏覽器)創建一個Seesion對象;
- 一個Seesion獨佔一個瀏覽器,只要瀏覽器沒有關閉,這個Session就存在;
- 用戶登錄之後,整個網站它都可以訪問!
Session和cookie的區別:
- Cookie是把用戶的數據寫給用戶的瀏覽器,瀏覽器保存 (可以保存多個)
- Session把用戶的數據寫到用戶獨佔Session中,服務器端保存 (保存重要的信息,減少服務器資源的浪費)
- Session對象由服務創建;
使用場景:
- 保存一個登錄用戶的信息;
- 購物車信息;
- 在整個網站中經常會使用的數據,我們將它保存在Session中;
Session的使用
得到session並向其中存放person對象,輸出sessionID信息
public class SessionDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解決中文亂碼問題
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
//得到Session
HttpSession session = req.getSession();
//向session中存東西
session.setAttribute("person",new Person("伊澤瑞爾",18));
//存放session id
String id = session.getId();
if (session!=null){
resp.getWriter().write("session創建成功,id爲:"+id);
}else {
resp.getWriter().write("session已經存在,id爲:"+id);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
後臺輸出session對象信息
public class SessionDemo02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解決中文亂碼問題
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
//得到Session
HttpSession session = req.getSession();
Person person = (Person) session.getAttribute("person");
System.out.println(person.toString());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
手動註銷session
public class SessionDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解決中文亂碼問題
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
//得到Session
HttpSession session = req.getSession();
session.removeAttribute("person");
//手動註銷session
session.invalidate();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
設置session失效時間
<session-config>
<!--設置session失效時間爲1分鐘-->
<session-timeout>1</session-timeout>
</session-config>
第一次訪問頁面創建了一個sessionID
訪問SessionDemo02後臺輸出session保存的person對象信息
訪問SessionDemo03註銷session
再次訪問SessionDemo01又新創建了一個session,id和第一次訪問的不同。
session實現購物車功能
jsp頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>請選擇你要購買的書籍</h1>
<form action="${pageContext.request.contextPath}/ShoppingCarDemo01" method="get">
<input type="checkbox" name="book" value="JavaSE"/>JavaSE <br/>
<input type="checkbox" name="book" value="JavaWeb"/>JavaWeb <br/>
<input type="checkbox" name="book" value="JavaEE"/>JavaEE <br/>
<input type="submit" value="提交">
</form>
</body>
</html>
處理書籍信息的servlet
public class ShoppingCarDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解決中文亂碼問題
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
//獲取session對象
HttpSession session = req.getSession();
Map<String,Integer> car = (Map<String, Integer>) session.getAttribute("shoppingCar");
if(car==null){
car = new HashMap<>();
}
//獲取客戶端數據
String[] books = req.getParameterValues("book");
if (books!=null && books.length>0){
for (String book : books) {
if (car.get(book)!=null){
int num = car.get(book);
car.put(book,num+1);
}else {
car.put(book,1);
}
}
}
session.setAttribute("shoppingCar",car);
//重定向到購物車頁面
resp.sendRedirect("/demo02_war/ShoppingCarDemo02");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
顯示購物車信息的servlet
public class ShoppingCarDemo02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解決中文亂碼問題
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
PrintWriter out = resp.getWriter();
//獲取session對象
HttpSession session = req.getSession();
Map<String,Integer> car = (Map<String, Integer>) session.getAttribute("shoppingCar");
if (car != null &&car.size()>0){
out.print("您購買的書籍有");
for (String bookName : car.keySet()) {
out.print("<p>"+bookName+":"+car.get(bookName)+"本<p>");
}
}else {
out.print("您還未購買任何書籍");
}
out.print("<p><a href='bookChoose.jsp'>繼續購買</a></p>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}