(JavaWeb)会话跟踪技术Cookie和Session(重点)
生活随笔
收集整理的這篇文章主要介紹了
(JavaWeb)会话跟踪技术Cookie和Session(重点)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- Cookie和Session
- 會話
- 保存會話的兩種技術
- Cookie
- 實現顯示上次訪問時間
- Session
- Session的使用
- session實現購物車功能
Cookie和Session
會話
會話:用戶打開一個瀏覽器,點擊了很多超鏈接,訪問多個web資源,關閉瀏覽器,這個過程可以稱之為會話;
有狀態會話:一個同學來過教室,下次再來教室,我們會知道這個同學,曾經來過,稱之為有狀態會話;
一個網站,怎么證明你來過?
客戶端 服務端
保存會話的兩種技術
cookie
- 客戶端技術 (響應,請求)
session
- 服務器技術,利用這個技術,可以保存用戶的會話信息? 我們可以把信息或者數據放在Session中!
常見場景:網站登錄之后,你下次不用再登錄了,第二次訪問直接就上去了!
Cookie
實現顯示上次訪問時間
public class CookieServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//解決中文亂碼問題resp.setContentType("text/html");req.setCharacterEncoding("utf-8");resp.setCharacterEncoding("utf-8");//獲取cookieCookie[] 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);//添加cookieresp.addCookie(cookie);}@Overrideprotected 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 {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//解決中文亂碼問題resp.setCharacterEncoding("utf-8");resp.setContentType("text/html;charset=utf-8");req.setCharacterEncoding("utf-8");//得到SessionHttpSession session = req.getSession();//向session中存東西session.setAttribute("person",new Person("伊澤瑞爾",18));//存放session idString id = session.getId();if (session!=null){resp.getWriter().write("session創建成功,id為:"+id);}else {resp.getWriter().write("session已經存在,id為:"+id);}}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }后臺輸出session對象信息
public class SessionDemo02 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//解決中文亂碼問題resp.setCharacterEncoding("utf-8");resp.setContentType("text/html;charset=utf-8");req.setCharacterEncoding("utf-8");//得到SessionHttpSession session = req.getSession();Person person = (Person) session.getAttribute("person");System.out.println(person.toString());}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }手動注銷session
public class SessionDemo03 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//解決中文亂碼問題resp.setCharacterEncoding("utf-8");resp.setContentType("text/html;charset=utf-8");req.setCharacterEncoding("utf-8");//得到SessionHttpSession session = req.getSession();session.removeAttribute("person");//手動注銷sessionsession.invalidate();}@Overrideprotected 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 {@Overrideprotected 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");}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }顯示購物車信息的servlet
public class ShoppingCarDemo02 extends HttpServlet {@Overrideprotected 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>");}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }
總結
以上是生活随笔為你收集整理的(JavaWeb)会话跟踪技术Cookie和Session(重点)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (JavaWeb)HttpServlet
- 下一篇: (JavaWeb)Filter过滤器