Cookie 实际上是一小段的文本信息。客户端请求服务器,如果服务器需要记录该用户状态,就使用 response 向客户端浏览器颁发一个 Cookie。客户端浏览器会把 Cookie 保存起来。当浏览器再请求该网 站时,浏览器把请求的网址连同该 Cookie 一同提交给服务 器。服务器检查该 Cookie,以此来辨认用户 状态。服务器还可以根据需要修改Cookie的内容。 cookie 就是服务器存放在浏览器的一小份数据(只能是字符串,并且不超过4kb),以后浏览器每次访问 我这个服务器都会将cookie携带过来。
Session 是另一种记录客户状态的机制,不同的是 Cookie 保存在客户端浏览器中,而 Session 保存 在服务器上。客户端浏览器访问服务器的时候,服务器把客户端信息以某种形式记录在服务器上。这就是 Session。客户端浏览器再次访问时只需要从该Session中查找该客户的状态就可以了。
如果说 Cookie 机制是通过检查客户身上的“通行证”来确定客户身份的话,那么 Session 机制就是 通过检查服务器上的“客户明细表”来确认客户身份。Session 相当于程序在服务器上建立的一份客户档 案,客户来访的时候只需要查询客户档案表就可以了。
问:request.getSession(true) 和 request.getSession(false)的区别 ?
request.getSession(true):若存在会话则返回该会话,否则新建一个会话。
request.getSession(false):若存在会话则返回该会话,否则返回 NULL
HttpServletRequest.getSession(true)等同于 HttpServletRequest.getSession() HttpServletRequest.getSession(false)等同于:如果当前 Session 没有就为 null
cookie 和session 的区别:
1、cookie 数据存放在客户的浏览器上,session数据放在服务器上。
2、cookie 不是很安全,别人可以分析存放在本地的COOKIE并进行COOKIE欺骗 考虑到安全应当使用session。
3、session会在一定时间内保存在服务器上。当访问增多,会比较占用你服务器的性能 考虑到减轻服务器性能方面,应当使用COOKIE。
4、单个cookie 保存的数据不能超过4K,很多浏览器都限制一个站点最多保存20个cookie。
5、所以个人建议: 将登陆信息等重要信息存放为SESSION 其他信息如果需要保留,可以放在COOKIE中。
简单购物车示例代码
1 package com.food.entity;
2
3 import java.math.BigDecimal;
4 import java.util.Iterator;
5 import java.util.Map;
6
7 /**
8 * 购物车
9 * 包括每一种菜品小项 总计每一种菜品数量(不包括相同的菜品)、总计金额
10 */
11 public class Car2 {
12 private int sumnum;//总数量数量
13 private int sumprice;//总金额
14 private Map<Integer,CarItem> map;//购物车中的每一项(每一个菜品信息)
15
16 public Car2() {
17 }
18
19 @Override
20 public String toString() {
21 return "Car2{" +
22 "sumnum=" + sumnum +
23 ", sumprice=" + sumprice +
24 ", map=" + map +
25 '}';
26 }
27
28 public int getSumnum() {
29 return sumnum;
30 }
31
32 public void setSumnum(int sumnum) {
33 this.sumnum = sumnum;
34 }
35
36 public int getSumprice() {
37 return sumprice;
38 }
39
40 public void setSumprice(int sumprice) {
41 this.sumprice = sumprice;
42 }
43
44 public Map<Integer, CarItem> getMap() {
45 return map;
46 }
47
48 /**
49 * 计算总数量与计算总价格
50 * @param map
51 */
52 public void setMap(Map<Integer, CarItem> map) {
53 int a = 0;
54 int b = 0;
55 Iterator<CarItem> i = map.values().iterator();
56 while (i.hasNext()){
57 CarItem c = i.next();
58 a+=c.getItemNum();
59 b+=c.getItemPrice();
60 }
61 this.sumnum=a;
62 this.sumprice=b;
63 this.map = map;
64 }
65 }
1 package com.food.entity;
2
3 import java.io.Serializable;
4 import java.math.BigDecimal;
5
6 /**
7 * 购物车中每一个小项
8 * 小项中包括food类中的 信息 与小计数量、小计金额
9 */
10 public class CarItem extends Food implements Serializable {
11 private int itemNum;//购物车中小项的菜品数量
12 private int itemPrice;//购物车中小项的菜品价格小计
13
14 public CarItem() {
15 }
16
17 @Override
18 public String toString() {
19 return "CarItem{" +
20 "itemNum=" + itemNum +
21 ", itemPrice=" + itemPrice +
22 '}';
23 }
24
25 public int getItemNum() {
26 return itemNum;
27 }
28
29 public void setItemNum(int itemNum) {
30 this.itemNum = itemNum;
31 }
32
33 public int getItemPrice() {
34 return this.getItemNum()*this.getFprice();
35 }
36
37 public void setItemPrice(int itemPrice) {
38 this.itemPrice = itemPrice;
39 }
40 }
1 package com.food.entity;
2
3 import java.io.Serializable;
4 import java.math.BigDecimal;
5
6 /**
7 * 菜品类
8 */
9 public class Food implements Serializable {
10 private int fid;//int(11) NOT NULL购物车id
11 private String fname;//varchar(20) NULL购物车商品名称
12 private String ftype;//varchar(20) NULL购物车中商品类型
13 private String fshop;//varchar(100) NULL购物车中的商品
14 private int fprice;//decimal(9,2) NULL价格
15 private String img;//varchar(30) NULL图片
16
17 @Override
18 public String toString() {
19 return "Food{" +
20 "fid=" + fid +
21 ", fname='" + fname + '\'' +
22 ", ftype='" + ftype + '\'' +
23 ", fshop='" + fshop + '\'' +
24 ", fprice=" + fprice +
25 ", img='" + img + '\'' +
26 '}';
27 }
28
29 public Food() {
30 }
31
32 public int getFid() {
33 return fid;
34 }
35
36 public void setFid(int fid) {
37 this.fid = fid;
38 }
39
40 public String getFname() {
41 return fname;
42 }
43
44 public void setFname(String fname) {
45 this.fname = fname;
46 }
47
48 public String getFtype() {
49 return ftype;
50 }
51
52 public void setFtype(String ftype) {
53 this.ftype = ftype;
54 }
55
56 public String getFshop() {
57 return fshop;
58 }
59
60 public void setFshop(String fshop) {
61 this.fshop = fshop;
62 }
63
64 public int getFprice() {
65 return fprice;
66 }
67
68 public void setFprice(int fprice) {
69 this.fprice = fprice;
70 }
71
72 public String getImg() {
73 return img;
74 }
75
76 public void setImg(String img) {
77 this.img = img;
78 }
79 }
1 package com.food.dao;
2
3 import com.food.entity.Food;
4 import com.food.util.DataBase;
5
6 import java.sql.SQLException;
7 import java.util.List;
8
9 /**
10 * 数据连接对象
11 */
12 public class FoodDao{
13
14 private DataBase db = new DataBase();
15
16 //查询全部菜品信息方法
17 public List<Food> getFoodList(){
18 String sql = "select * from tblfood";
19 try {
20 return db.executeQueryList(sql);
21 } catch (SQLException e) {
22 e.printStackTrace();
23 throw new RuntimeException("sql异常");
24 }
25 }
26
27 /**
28 * 根据id查询对应的菜品
29 * @param id
30 * @return
31 */
32 public Food findFoodById(Integer id){
33 String sql = "select * from tblfood where fid = ?";
34 try {
35 return db.executeQuery(sql,id);
36 } catch (SQLException e) {
37 e.printStackTrace();
38 throw new RuntimeException("sql异常");
39 }
40 }
41
42 }
1 package com.food.servlet;
2
3 import com.food.dao.FoodDao;
4 import com.food.entity.Car;
5 import com.food.entity.Car2;
6 import com.food.entity.CarItem;
7 import com.food.entity.Food;
8
9 import javax.servlet.ServletException;
10 import javax.servlet.annotation.WebServlet;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14 import javax.servlet.http.HttpSession;
15 import java.io.IOException;
16 import java.math.BigDecimal;
17 import java.util.HashMap;
18 import java.util.Map;
19
20 @WebServlet("/food")
21 public class FoodServlet extends HttpServlet {
22 //需要一个dao对象
23 private FoodDao foodDao = new FoodDao();
24
25 /**
26 * dopost,根据参数名判断进入哪一个servlet
27 * @param request
28 * @param response
29 * @throws ServletException
30 * @throws IOException
31 */
32 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
33 doGet(request,response);
34 }
35
36 /**
37 * doget
38 * @param request
39 * @param response
40 * @throws ServletException
41 * @throws IOException
42 */
43 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
44 String param = request.getParameter("param");//param=list
45 if (!(param==null || "".equals(param))){
46 if ("list".equals(param)){展示所有的菜品信息
47 foodlist(request,response);
48 } else if ("add".equals(param)) {//点餐
49 foodadd(request,response);
50 } else if ("view".equals(param)) {//查看购物车
51 foodview(request,response);
52 } else if ("removeall".equals(param)){
53 foodremoveall(request,response);
54 } else if("change".equals(param)){
55 foodchange(request,response);
56 }else{
57 throw new RuntimeException("参数错误。。。。");
58 }
59 }
60
61 }
62
63 /**
64 * 购物车中加-减按钮servlet
65 * @param request
66 * @param response
67 * @throws IOException
68 */
69 private void foodchange(HttpServletRequest request, HttpServletResponse response) throws IOException {
70 HttpSession session = request.getSession();
71 Car2 car = (Car2) session.getAttribute("car");
72 Map<Integer, CarItem> map = car.getMap();
73 String cha = request.getParameter("cha");
74 String fid = request.getParameter("fid");
75 CarItem carItem = map.get(Integer.parseInt(fid));
76 if ("jian".equals(cha)){
77 if (carItem.getItemNum()-1<1){
78 carItem.setItemNum(0);
79 }else{
80 carItem.setItemNum(carItem.getItemNum()-1);
81 }
82 }else if ("jia".equals(cha)){
83 carItem.setItemNum(carItem.getItemNum()+1);
84 }
85 map.put(Integer.parseInt(fid),carItem);
86 car.setMap(map);
87 session.setAttribute("car",car);
88 response.sendRedirect("/html/foodcar.jsp");
89 }
90
91 /**
92 * 购物车中移除按钮servlet
93 * @param request
94 * @param response
95 * @throws IOException
96 */
97 private void foodremoveall(HttpServletRequest request, HttpServletResponse response) throws IOException {
98 String fid = request.getParameter("fid");
99 HttpSession session = request.getSession();
100 Car2 car = (Car2)session.getAttribute("car");
101 Map<Integer, CarItem> map = car.getMap();
102 map.remove(Integer.parseInt(fid));
103 car.setMap(map);
104 session.setAttribute("car",car);
105 response.sendRedirect("/html/foodcar.jsp");
106 }
107
108 /**
109 * 菜品展示servlet
110 * @param request
111 * @param response
112 * @throws IOException
113 */
114 private void foodview(HttpServletRequest request, HttpServletResponse response) throws IOException {
115 response.sendRedirect("/html/foodcar.jsp");
116 }
117
118 /**
119 * 菜品添加servlet
120 * @param request
121 * @param response
122 * @throws ServletException
123 * @throws IOException
124 */
125 private void foodadd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
126 //获取菜品id
127 String foodid = request.getParameter("foodid");
128 //找到菜品
129 Food food = foodDao.findFoodById(Integer.parseInt(foodid));
130 //构造一个session
131 HttpSession session = request.getSession();
132 //从session中拿购物车(car)对象
133 Object obj = session.getAttribute("car");
134 //声明一个map对象
135 Map<Integer,CarItem> map = null;
136 //构造一个空的购物车
137 Car2 car = new Car2();
138 if (obj == null){//第一次添加到购物车
139 //构造一个map对象
140 map = new HashMap<>();
141 //构造子项
142 CarItem i = new CarItem();
143 i.setImg(food.getImg());
144 i.setFname(food.getFname());
145 i.setFshop(food.getFshop());
146 i.setFtype(food.getFtype());
147 i.setFid(food.getFid());
148 i.setFprice(food.getFprice());
149 //小计金额与小计数量
150 i.setItemNum(1);
151 i.setItemPrice(food.getFprice()*1);
152 //添加到集合中
153 map.put(food.getFid(),i);
154 }else {//购物车中有小项
155 //判断添加的菜品是否有重复的,怎么判断?
156 map = ((Car2)obj).getMap();//转换为购物车对象,从购物车中拿到map对象
157 boolean b = map.keySet().contains(food.getFid());//根据菜品的id判断
158 if (b){//重复的菜品,数量加一,小计已经在CarItem类中计算了
159 CarItem carItem = map.get(food.getFid());
160 carItem.setItemNum(carItem.getItemNum()+1);
161 }else{//不是重复的菜品
162 //构造子项
163 CarItem i = new CarItem();
164 i.setImg(food.getImg());
165 i.setFname(food.getFname());
166 i.setFshop(food.getFshop());
167 i.setFtype(food.getFtype());
168 i.setFid(food.getFid());
169 i.setFprice(food.getFprice());
170 //小计金额与小计数量
171 i.setItemNum(1);
172 i.setItemPrice(food.getFprice()*1);
173 //添加到集合中
174 map.put(food.getFid(),i);
175 }
176 }
177 System.out.println("总金额"+car.getSumnum()+car.getSumprice());
178 car.setMap(map);
179 session.setAttribute("car",car);
180 response.sendRedirect("/html/foodcar.jsp");
181 }
182
183 /**
184 * 菜品列表servlet
185 * @param request
186 * @param response
187 * @throws ServletException
188 * @throws IOException
189 */
190 private void foodlist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
191 request.setAttribute("flist",foodDao.getFoodList());
192 request.getRequestDispatcher("/html/foodlist.jsp").forward(request,response);
193 }
194 }
1 package com.food.util;
2
3 import com.food.entity.Food;
4 import org.apache.commons.dbutils.QueryRunner;
5 import org.apache.commons.dbutils.handlers.BeanHandler;
6 import org.apache.commons.dbutils.handlers.BeanListHandler;
7
8 import java.sql.SQLException;
9 import java.util.List;
10
11 public class DataBase {
12
13 private QueryRunner runner = new QueryRunner(DataUtil.getDataSource());
14
15 public int executeUpdate(String sql,Object ... params) throws SQLException {
16 return runner.update(sql,params);
17 }
18 // new ScalarHandler()用于聚合函数
19 //new BeanListHandler<>用于查询集合
20 //new BeanHandler<>用于查询一个对象
21 public List<Food> executeQueryList(String sql,Object ... params) throws SQLException {
22 return runner.query(sql,new BeanListHandler<>(Food.class),params);
23 }
24
25 public Food executeQuery(String sql,Object ... params) throws SQLException {
26 return runner.query(sql,new BeanHandler<>(Food.class),params);
27 }
28 }
1 package com.food.util;
2
3 import com.mchange.v2.c3p0.ComboPooledDataSource;
4
5 import javax.sql.DataSource;
6 import java.sql.Connection;
7 import java.sql.SQLException;
8
9 /**
10 * 数据源
11 */
12 public class DataUtil {
13 private static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql");
14
15 public static DataSource getDataSource(){
16 return dataSource;
17 }
18
19 public static Connection getConnection(){
20 try {
21 return dataSource.getConnection();
22 } catch (SQLException e) {
23 e.printStackTrace();
24 throw new RuntimeException("获取connection对象失败");
25 }
26 }
27
28 public static void close(Connection con){
29 if (con!=null){
30 try {
31 con.close();
32 } catch (SQLException e) {
33 e.printStackTrace();
34 }
35 }
36 }
37 }
1 package com.food.filter;
2
3 import javax.servlet.*;
4 import javax.servlet.annotation.WebFilter;
5 import java.io.IOException;
6
7 @WebFilter("/*")
8 public class FoodProFilter implements Filter {
9 public void destroy() {
10 }
11
12 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
13 req.setCharacterEncoding("utf-8");
14 resp.setCharacterEncoding("utf-8");
15 chain.doFilter(req, resp);
16 }
17
18 public void init(FilterConfig config) throws ServletException {
19
20 }
21
22 }
1 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
2 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
3 <html>
4 <head>
5 <title>我的购物车</title>
6 <%--导入bootstrap框架--%>
7 <link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css">
8 <script src="../bootstrap/js/jquery.min.js"></script>
9 <script src="../bootstrap/js/bootstrap.min.js"></script>
10 </head>
11 <body>
12
13 <div class="container">
14
15 <div class="panel panel-primary">
16 <div class="panel-heading">
17 <h1>我的购物车</h1>
18 </div>
19 <div class="panel-body">
20
21 <table class="table table-striped table-bordered table-hover text-center">
22
23 <tr>
24 <td>编号</td>
25 <td>图片</td>
26 <td>菜名</td>
27 <td>风味</td>
28 <td>餐馆</td>
29 <td>价格</td>
30 <td>数量</td>
31 <td>小计</td>
32 <td>操作</td>
33 </tr>
34
35 <c:forEach items="${car.map}" var="m">
36 <tr>
37 <td>${m.value.fid}</td>
38 <td><img width="35px" src="../${m.value.img}"/></td>
39 <td>${m.value.fname}</td>
40 <td>${m.value.ftype}</td>
41 <td>${m.value.fshop}</td>
42 <td>${m.value.fprice}.00元</td>
43 <td>
44 <a href="/food?param=change&cha=jian&fid=${m.value.fid}" style="text-decoration: none;" class="btn btn-primary glyphicon glyphicon-minus"></a>
45 ${m.value.itemNum}
46 <a href="/food?param=change&cha=jia&fid=${m.value.fid}" style="text-decoration: none;" class="btn btn-primary glyphicon glyphicon-plus"></a>
47 </td>
48 <td>${m.value.itemPrice}.00元</td>
49 <td>
50 <a class="btn btn-danger" href="/food?param=removeall&fid=${m.value.fid}">移除全部</a>
51 </td>
52 </tr>
53 </c:forEach>
54
55 <tr>
56 <td colspan="9">
57 数量共:${car.sumnum}件, 总金额:${car.sumprice}.00元,
58 </td>
59 </tr>
60
61 </table>
62 <a class="btn btn-success btn-lg btn-block" href="/food?param=list">继续点餐</a>
63 </div>
64
65 <div class="panel-footer text-right">
66 海底捞列表页
67 </div>
68 </div>
69
70 </div>
71
72 </body>
73 </html>
1 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
2 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
3 <html>
4 <head>
5 <title>海底捞列表页</title>
6 <link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css">
7 <script src="../bootstrap/js/jquery.min.js"></script>
8 <script src="../bootstrap/js/bootstrap.min.js"></script>
9 </head>
10 <body>
11 <div class="container">
12 <div class="panel panel-primary">
13 <div class="panel-heading">
14 <h1>海底捞列表页</h1>
15 </div>
16 <div class="panel-body">
17 <div class="form-group">
18 <div class="row">
19 <c:forEach items="${flist}" var="f">
20 <div class="col-md-3">
21 <div class="thumbnail">
22 <img src="../${f.img}">
23 <div class="caption">
24 <h5>${f.fname}(${f.fshop}:${f.ftype})</h5>
25 <p>¥:${f.fprice}元</p>
26 <p>
27 <a href="/food?param=add&foodid=${f.fid}" class="btn btn-primary" role="button">开始点餐</a>
28 <a href="#" class="btn btn-warning" role="button">查看评论</a>
29 </p>
30 </div>
31 </div>
32 </div>
33 </c:forEach>
34 </div>
35 </div>
36 <a href="/food?param=view" class="btn btn-primary col-md-3 btn-lg" style="float: right;">查看购物车</a>
37 </div>
38 <div class="panel-footer text-right">
39 海底捞列为您服务
40 </div>
41 </div>
42 </div>
43 </body>
44 </html>