Cookie&Session
Cookie
用户第一次登陆之后服务器返回的数据,存储在用户本地,但数据量有限,不同的浏览器有不同的存储大小,但一般不超过4KB。因此使用cookie只能存储一些小量的数据。
Session
存储在服务器的数据。
Cookie的用途:
获取用户上次的登陆时间
获取浏览记录
Session的实例实现:
简单购物车:
1.goods.jsp(点击超链接,交由Servlet处理,加购物车)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <div> <a href="AddToShopcar?id=iphone">iphone</a> </div> <div> <a href="AddToShopcar?id=iphone10">iphone10</a> </div> <div> <a href="AddToShopcar?id=iphoner">iphoner</a> </div> <div> <a href="AddToShopcar?id=mbp">mbp</a> </div> <div> <a href="AddToShopcar?id=sony">sony</a> </div> <div> <a href="AddToShopcar?id=kindle">kindle</a> </div> </body> </html>
2.Servlet实现(web.xml的配置可参考)
package nee; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; @WebServlet(name = "AddToShopcarServlet") public class AddToShopcarServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); String good=request.getParameter("id"); HttpSession session= request.getSession(); Map<String,Integer> map= (Map<String,Integer>)session.getAttribute("shopcar"); // 第一次加购物车 if(map == null){ map=new LinkedHashMap<String, Integer>(); map.put(good,1); } else { //如果已在购物车中,数量加1 if(map.containsKey(good)) { map.put(good, map.get(good) + 1); } else { map.put(good, 1); } } session.setAttribute("shopcar",map); response.getWriter().write("<div><a href=goods.jsp>继续购物</a></div>"); response.getWriter().write("<div><a href=shopcar.jsp>查看购物车</a></div>"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } }
3.shopcar.jsp --动态加入session的内容
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <% Map<String,Integer> map=(Map<String,Integer>)request.getSession().getAttribute("shopcar"); for(String s:map.keySet()){ Integer i =map.get(s); %> <p><%=s%> <%=i%></p> <% } %> </body> </html>
未使用EL和JSTL,下几篇开始写相关内容及实例。