##場景 在WEB開發中,服務器中能夠爲每一個用戶瀏覽器建立一個會話對象(session對象),注意:一個瀏覽器獨佔一個session對象(默認狀況下),當瀏覽器訪問其它程序時,其它程序能夠從用戶的session中取出該數據,爲用戶服務。 session和cookie的主要區別在於: cookie技術是把用戶的數據寫給用戶的瀏覽器 session技術把用戶的數據寫到用戶獨佔的session中 session對象由服務器建立,開發人員能夠調用request對象的getSession方法獲得session對象。html
request.getSession(false) 只獲取,不建立web
##session的實現原理 ###原理 session是基於cookie的session是一個沒有設定maxAge的cookie瀏覽器
###如何防止關閉瀏覽器後存儲的用戶信息被刪除 思路:向客戶端回寫一個名稱與session相同的cookie覆蓋,並設定maxAge服務器
HttpSession session = request.getSession(); String sessionId = session.getId() Cookie cookie = new Cookie("JSESSIONID",sessionId); cookie.setPath(requst.getContextPath()); cookie.setMaxAge(30*60); session.setAttribute("name","洗衣機");
##session的工做原理 ###用戶瀏覽器禁用cookie的解決方案cookie
response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter pw = response.getWriter(): request.getSession(); String url1 = response.encodeURL("/test-web/servlet/sessionDemo1"); String url2 = response.encodeURL("/test-web/servlet/sessionDemo2"); pw.print("<a href='"+url1+"'>購買</a><br/><a href="'" + url2 + "'>收藏</a>"); //response.encodeURL()方法將自動判斷瀏覽器是否禁用cookie,若禁用,則重寫URL,後面拼接JSESSIONID
##用session完成簡單的購物session
public class ListAllServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); HttpSession session = request.getSession(); PrintWriter pw = response.getWriter(); pw.print("本網站有以下商品: <br/>"); Map<Integer, Book> map = Db.getAll(); Set<Entry<Integer, Book>> entrySet = map.entrySet(); for (Entry<Integer, Book> entry : entrySet) { Book book = entry.getValue(); String url = response.encodeURL("/test-web/BuyServlet?id=" + book.getId()); pw.print(book.getName() + "<a href='" + url + "' target=_blank>購買</a><br/>"); } pw.print("當前已經購買了:<br/>"); List<Book> list = (List<Book>) session.getAttribute("list"); if (list != null) { for (Book book : list) { if(book!=null){ pw.print(book.getName()+"<br/>"); } } } } }
public class BuyServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); Book book = Db.getAll().get(Integer.valueOf(id)); HttpSession session = request.getSession(false); List list = (List) session.getAttribute("list"); if (list == null) { list = new ArrayList<Book>(); } list.add(book); session.setAttribute("list", list); String url = request.getContextPath() + "/ListAllServlet"; url = response.encodeRedirectUrl(url); response.sendRedirect(url); // 此處用rediret 防止刷新再次購買 } }