avatar

电子购物商城项目

项目傻瓜式流程

GitHub地址:https://github.com/panyongkang/gitRepository/tree/master/e-shop

案例1-用户注册

需求:在register.jsp页面填写数据信息,点击保存,将数据信息保存到数据库中。  
步骤分析:  
1.点击注册,跳转链接到register.jsp页面  
2.在form表单action中跳转到userRegister方法  
3.在userServlet中编写userRegister方法    
方法中思路步骤:  
获取前台数据参数,并封装成user对象  
手动封装数据  
调用service方法完成注册  
显示提示信息,跳转注册成功页面  
4.在userService中:
调用dao方法完成注册  
发送邮件  
5.在userDao中:  
获取数据源  
拼写sql语句,执行insert操作。  

案例2-用户激活

需求:用户登录邮箱后,点击邮箱中的链接,完成用户激活操作  
步骤分析:  
1.点击邮箱中的链接,向商场userServlet发送一个请求user?method=activeUser&coed=xxxx  
2.在userServlet中编写active方法  
2.1接收code参数  
2.2调用service方法完成激活  
2.3生成提示信息 转发  
    3.在service中编写激活方法  
        通过code获取用户  
            若没有找到:提示重新激活或者重新注册  
            若找到了:  
                设置激活状态为1  
                将code设置为null  
    4.在dao中编写两个方法  
        GetByCode()  
        Update()  

案例3-用户登录

需求:在一个登录页面上,输入用户名和密码,点击登录,完成登录操作  
步骤分析:  
1.在ingdex.jsp中点击登录,跳转到登录页面login.jsp  
2.在userServlet中编写loginUI  
3.修改login.jsp表单的信息  
    action:/user?method=login  
    method  
    给子标签添加name属性  
4.点击提交发送请求  
5.在userServlet中编写login方法  
获取用户名和密码  
调用service完成登录 返回值:user  
若登录成功,跳转到index.jsp,并显示用户信息  
若登录失败,若user为空:提示用户名和密码,跳转到login.jsp  
若user不为空但是未激活:提示“请先去邮箱激活,在登录” 跳转msg.jsp   
6.service,dao  
login.jsp表单登录代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<form class="form-horizontal" id="loginForm" method="post" action="${pageContext.request.contextPath }/user?method=userLogin">
<div class="form-group">
<label for="username" class="col-sm-2 control-label">用户名</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="username" name="username"
placeholder="请输入用户名">
</div>
<label id="username-error" class="error" for="username"> </label>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">密码</label>
<div class="col-sm-6">
<input type="password" class="form-control" id="password" name="password"
placeholder="请输入密码">
</div>
<label id="password-error" class="error" for="password"> </label>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">验证码</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="checkCode" name="checkCode"
placeholder="请输入验证码">
</div>
<div class="col-sm-3">
<img src="${pageContext.request.contextPath }/checkImg" onclick="changeCheckImg(this)" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label> <input type="checkbox"> 自动登录
</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <label>
<input type="checkbox" name="savename" value="ok" > 记住用户名
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" width="100" value="登录" name="submit"
style="background: url('./images/login.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0); height: 35px; width: 100px; color: white;">
</div>
</div>
<div id="loginInfo" style="padding-left: 50px; color: red;">
<c:if test="${loginInfo=='false' }">
用户名或密码输入错误
</c:if>
<c:if test="${loginInfo=='notActive' }">
用户尚未激活
</c:if>
</div>
</form>
Js验证信息代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//登录表单验证
$("#loginForm").validate({
rules:{
username:{
required:true
},
password:{
required:true
},
checkCode:{
required:true,
isRight:true
}

},
messages:{
username:{
required:"请输入用户名"
},
password:{
required:"请输入密码"
},
checkCode:{
required:"请输入验证码",
isRight:"验证码不正确"
}

}
});
UserServlet.java代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* 用户登录
* @param request
* @param response
* @throws IOException
*/
public void userLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
Map<String, String[]> properties = request.getParameterMap();
User loginUser = new User();
try {
BeanUtils.populate(loginUser, properties);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
UserService service = new UserService();
User user = service.login(loginUser);
if (user == null) {
// 表示用户不存在
request.getSession().setAttribute("loginInfo", "false"); // 将登陆信息存到session中
response.sendRedirect(request.getContextPath() + "/login.jsp");
} else {
if (user.getState() == 0) {
// 表示用户尚未激活
request.getSession().setAttribute("loginInfo", "notActive");
response.sendRedirect(request.getContextPath() + "/login.jsp");
} else {
// 表示登陆成功
request.getSession().setAttribute("user", user);

/************************记住用户名:判断是否勾选了记住用户名**************/
if(Constant.SAVE_NAME.equals(request.getContextPath())) {
Cookie c= new Cookie("saveName", java.net.URLEncoder.encode(user.getUsername(), "utf-8"));
c.setMaxAge(Integer.MAX_VALUE);//设置保存时间
c.setPath(request.getContextPath()+"/");//指定一个路径
response.addCookie(c);
}

response.sendRedirect(request.getContextPath());
}
}
}
UserService.java代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
	/**
* 用户登陆
* @param user
* @return
*/
public User login(User loginUser) {
UserDao dao = new UserDao();
User user = null;
try {
user = dao.isRight(loginUser);
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
UserDao.java代码:
/**
* 查询用户名和密码是否正确
* @param user
* @return
* @throws SQLException
*/
public User isRight(User user) throws SQLException {
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from user where username=? and password=?";
return runner.query(sql, new BeanHandler<User>(User.class), user.getUsername(),user.getPassword());
}
Login.jsp验证码验证代码:
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">验证码</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="checkCode" name="checkCode"
placeholder="请输入验证码">
</div>
<div class="col-sm-3">
<img src="${pageContext.request.contextPath }/checkImg" onclick="changeCheckImg(this)" />
</div>
Js部分代码:
//更换验证码
function changeCheckImg(obj) {
$(obj).attr("src","${pageContext.request.contextPath }/checkImg?date="+new Date());
}
$(function(){
//自定义校验规则------验证码是否正确
$.validator.addMethod("isRight",function(value,element,params){
var varify = false;
$.ajax({
//设置为同步校验,(同步就是多任务串行,服务器没有响应之前,不允许进行其他操作)
async:false,
dataType:"json",
type:"POST",
data:{"checkCode":value},
url:"${pageContext.request.contextPath }/user?method=checkCodeVarify",
success:function(data){
varify = data.isRight;
}
});
return varify;
});
进入CheckImgServlet.java中执行验证码生成程序代码:
生成验证码后,输入验证码,验证码是否正确
进入UserServlet.java中执行方法:
/**
* 验证码验证
* @param request
* @param response
* @throws IOException
*/
public void checkCodeVarify(HttpServletRequest request, HttpServletResponse response) throws IOException {
String checkCode = (String) request.getParameter("checkCode");
Boolean isRight = checkCode.equals(request.getSession().getAttribute("checkcode_session"));
response.getWriter().write("{\"isRight\":" + isRight + "}");
}

案例4-用户退出

需求:点击index.jsp上 退出链接,退出当前用户,跳转index.jsp  
步骤分析:  
1.点击index.jsp 退出链接  
/user?method=logout  
2.在userservlet中编写logout方法  
销毁session  
重定向到index.jsp  
Header.jsp代码展示
1
<li><a href="${pageContext.request.contextPath }/user?method=quitUser">退出</a></li>
进入UserServlet.java代码
1
2
3
4
5
public String quitUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.getSession().invalidate();//用于清除session的所有信息。
response.sendRedIrect(request.getContextPath());
return null;
}

扩展案例-记住用户名

需求:登录成功后,若勾选了记住用户名,下次在登录的时候,会展示出来用户名  
步骤分析:  
    修改login方法的逻辑  
        登录成功后,判断是否勾选了记住用户名  
        若勾选了,将用户名(将用户名编码)保存到cookie中  
    在login.jsp加载成功的时候需要从cookie中获取用户名且展示出来  
Login.jsp代码展示
1
<input type=”checkbox” name=”savename” value=”ok”>记住用户名
进入UserServlet.java代码
1
2
3
4
5
6
7
8
9
	Request.getSession().setAttribute(“user”,user);
//判断是否勾选了记住用户名
If(Constant.SAVE_NAME.equals(request.getContextPath))){
Cookie c=new Cookie(“saveName”,java.net.URLEncoder.encode(user.getUsername(),”utf-8));
c.setMaxAge(Integer.MAX_VALUE);
c.setPath(request.getContextPath()+”/”);
response.addCookie(c);
}
response.sendRedirect(request.getContextPath());
Constant.java代码
1
2
//记住用户名常量,和value值一致
String SAVE_NAME="ok";

案例5-前台分类信息展示

需求:访问任意页面的时候,都需要将分类的信息展示出来  
技术分析:    
    包含(静态包含和动态包含)  
    Ajax技术  
步骤分析:  
1.创建分类表  
2.抽取所有页面上,logo和菜单部分(head.jsp)  
页面加载的时候  
Header.jsp代码
1
<ul class="nav navbar-nav" id="categoryUl"></ul>
编写函数  
        发送ajax请求,$.post(url,param,fn,type);  
                url:/store/category  
                params:method=findAll  
                fn:将返回值遍历,每一个分类封装成li标签,插入到ul标签内部  
                type:json  
Ajax详情链接:https://blog.csdn.net/huileiforever/article/details/12163385  
Header.jsp代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//使用JSON完成导航栏,然后利用js生成的li插入ul内部
$(function(){
//发送ajax请求,查询所有分类
//dataType:"json" - 以 JSON 运行响应,并以 JavaScript 对象返回
$.post(
"${pageContext.request.contextPath }/product?method=productCategory",
function(data){
var content ="";
for (var i = 0; i < data.length; i++) {//遍历json列表,获取每一个分类,包装成li标签
content +="<li><a href='${pageContext.request.contextPath}/product?method=product_list&cid="+data[i].cid+"'>"+data[i].cname+"</a></li>";
}
//插入到ul内部
$("#categoryUl").html(content);

},
"json"
);
});
编写ProductServlet,继承baseservlet,编写productCategory方法  
        调用service,查询所有的分类  
        分类列表的json字符串(String)  
        写回页面  
ProductServlet.java代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 查询商品分类
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void productCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ProductService service = new ProductService();
//查询所有商品类别
List<Category> categoryList = service.findAllCategory();
//将categoryList转为json字符串
Gson gson = new Gson();
String json = gson.toJson(categoryList);
response.setContentType("text/html; charset=UTF-8");
response.getWriter().write(json);
}
ProductService中的操作
调用dao,获取所有的分类
将list转成json返回
ProductService.java代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* 找所有商品类别
* @return
*/
public List<Category> findAllCategory() {
ProductDao dao = new ProductDao();
List<Category> categoryList = null;
try {
categoryList = dao.findCategory();
} catch (SQLException e) {
e.printStackTrace();
}
return categoryList;
}
ProductDao.java代码
1
2
3
4
5
6
7
8
9
10
/**
* 查询所有商品类别
* @return
* @throws SQLException
*/
public List<Category> findCategory() throws SQLException {
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from category";
return runner.query(sql, new BeanListHandler<Category>(Category.class));
}

3.在所有的页面里将head.jsp包含进去

获取返回值(json字符串)  
遍历返回值  
每一个分类封装成li标签,插入到ul标签内部  
    另一种方法:可使用redis进行优化(理解:因为每一个分类的数据,每点一次需要进行数据库访问,redis可以将数据保存在内存中,不用一直访问数据库)  
        修改service层的代码  
            获取的时候,去redis中获取  
                若获取到了返回
                若没有获取到,先去Mysql数据库中查询出来,将list转成json放入redis中即可

案例6-最新商品和热门商品展示

需求:  
    访问首页时,需要将最新商品和热门商品展示出来  
技术分析:  
    方式1:ajax异步(麻烦,导航栏就是异步)  
    方式2:同步  

采用同步方法的步骤分析(请求转发:因为路径不变,数据改变)  

    0.创建商品表

CREATE TABLE `product` (
  `pid` varchar(32) NOT NULL,
  `pname` varchar(50) DEFAULT NULL,
  `market_price` double DEFAULT NULL,
  `shop_price` double DEFAULT NULL,
  `pimage` varchar(200) DEFAULT NULL,
  `pdate` date DEFAULT NULL,
  `is_hot` int(11) DEFAULT NULL,
  `pdesc` varchar(255) DEFAULT NULL,
  `pflag` int(11) DEFAULT NULL,
  `cid` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`pid`),
  KEY `sfk_0001` (`cid`),
  CONSTRAINT `sfk_0001` FOREIGN KEY (`cid`) REFERENCES `category` (`cid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
插入数据:
INSERT INTO `product` VALUES ('1','小米 4c 标准版',1399,1299,'products/1/c_0001.jpg','2015-11-02',1,'小米 4c 标准版 全网通 白色 移动联通电信4G手机 双卡双待',0,'1'),(…一共50条不同记录);

1.访问项目首页,请求转发indexservlet
2.Indexservlet中使用默认index处理
    调用productservice查询热门商品和最新商品,每一个都返回一个list
    将两个list放入request域中,请求转发到index.jsp中
3.在页面中将数据遍历出来

案例7-单个商品详情

需求:在首页上点击每个商品,将这个商品的详细信息展示在页面(product_info.jsp)  
步骤分析:  
1.给每个商品添加超链接  
2.编写productservlet,继承baseservlet,编写getById  
获取商品的pid  
调用service获取一个商品,返回值:product  
请求转发到product_info.jsp  
3.service,dao  
4.在product_info.jsp中展示商品  

案例8-分类商品的分页展示

需求:点击菜单栏上某一个分类的时候,将该分类下的商品,分页展示出来(默认第一页)  
技术分析:  
    分页:  
        页面上需要的数据  
        当前页数据  
        当前页  
        总页数  
        总记录数  
        每页显示的条数  
    Limit m,n  
        Limit(当前页-1)*每页显示的条数,每页显示的条数  
步骤分析:  
1.修改head.jsp上的每个分页的超链接  
2.在cateservlet中编写findByPage方法  
获取参数  
获取cid  
设置pageSize  
调用service获取分页的数据,返回值:PageBean  
将pagebean放入request域中,请求转发  
3.编写service  
返回值:pagebean  
创建一个pagebean  
设置当前页需要的数据  
    调用dao  
设置总记录数  
    调用dao  
4.dao  
5.在product_list.jsp上展示商品  

案例9-添加到购物车

需求:在商品的详情页面输入购买数量,点击加入购物车,将该商品添加到购物车
技术分析:  
    Session  
涉及到实体:  
    购物车(cart)  
            属性:  
                购物项(商品购买信息)的集合  
                    Map<String,CartItem>  
                总金额(total)  
            方法:  
                加入购物车  
                    Add2Cart(Cartem,item){
                            //1.判断购物车是否有该商品
                            有:
                                修改购买数量(原来的数量+item.getCount())
                                修改总金额(原来的金额+item.getSubtotal())
                            无:直接put进去
                                修改总金额(原来金额+item.getSubtotal())
                         }
                从购物车移除  
                    removeFromCart(pid){ 
                            从map中移除指定购物项
                            修改总金额
                        }
                清空购物车  
                    clearCart(){ 
                            清空map
                            修改总金额=0.0
                        }
    购物项(CartItem)  
        属性:  
            商品对象(product)  
            购买数量(count)  
            小计(subtotal)  
        方法:  
            重新编写getSubtoal(){
                    Return product.getShop_price*count
                }
步骤分析
1.修改商品详情页面(product_info.jsp)  
添加一个表单:  
        要执行方法:onclick="addToCart()”          
        商品的pid:pid=xxx  
        商品的购买数量:count=xxx  
    点击“加入购物车”,将表单提交/store/cart  
    2.编写cartServlet    继承baseservlet,编写add2cart  
        获取商品的pid和count  
        封装cartitem  
            New cartitem(Product,count)  
        将cartitem加入购物车  
        获取购物车(session中获取)  
        调用购物车的add2cart方法即可  
重定向cart.jsp上  
Product_info.jsp部分代码
1
2
3
4
5
6
7
8
9
<a href=”javascript:void(0)” onclick=”addToCart()”>
<input style="background: url('./images/product.gif') no-repeat scroll 0 -600px rgba(0, 0, 0, 0); height: 36px; width: 127px;" value=”加入购物车” type=”button”></a>

<script type=”text/javascript”>
Function addToCart(){
Var proNum=$.(“#proNum”).val();//获取商品数量
Window.loacation=”${pageContext.request.contextPath}/cart?method=addToCart&pid=${product.pid}&proNum=”+proNum;
}
</script>
CartServlet.java代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
	//添加到购物车方法
public void addToCart(HttpServletRequest request, HttpServletResponse response) throws IOException {
String pid=request.getParameter(“pid”);
ProductService service = new ProductService();
Product product =service.findProductByPid(pid);
Int proNum=Integer.parseInt(request.getParameter(“proNum”));
HttpSession session=request.getSession();
//更新session域中的购物车对象
Cart cart=(Cart) session.getAtrribute(“cart”);
If(cart==null){
cart=new Cart();
}
Map<String,CartItem> cartMap=cart.getCartMap();
//判断商品的pid
If(cartMap.containsKey(pid){
//有:原来的购物项+新增的值
CartItem cartItem =cartMap.get(pid);
//购物车中已经包含了该商品:新加的数量+原来的数量
cartItem.setProNum(cartItem.getProductNum()+proNum);
//设置:小计的价格=新加的价格+购物车原来的价格
cartItem.setSubTotal(cartItem.getSubTotal()+product.getShop_price()*proNum);
cartMap.put(pid,cartItem);//将value值覆盖
}else{
//购物车中没有该商品,新增该购物商品项
CartItem cartItem=new CartItem();
cartItem.setProNum(proNum);
cartItem.setProduct(product);
cartItem.setSubToal(product.getShop_price()*proNum);
cartMap.put(pid,cartItem);
}
//修改当前购物车总金额
Cart.setToal(cart.getTotal()+product.getShop_price()*proNum);
Cart.setCartMap(cartMap);
Session.setAttribute(“cart”,cart);
//重定向到cart.jsp页面
response.sendRedirect(request.getContextPath()+”/cart.jsp”);
}
ProductService.java代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 单个商品查询
* 根据商品id找到商品
* @param pid
* @return
*/
public Product findProductByPid(String pid) {
ProductDao dao = new ProductDao();
Product product = null;
try {
product = dao.findProductByPid(pid);
} catch (SQLException e) {
e.printStackTrace();
}
return product;
}
ProductDao.java代码
1
2
3
4
5
6
7
8
9
10
11
/**
* 查询单个商品
* @param pid
* @return
* @throws SQLException
*/
public Product findProductByPid(String pid) throws SQLException {
QueryRunner runner=new QueryRunner(DataSourceUtils.getDataSource());
String sql=”select * from prduct where pid=?”;
Return runner.query(sql,new BeanHandler<Product>(Product.class),pid);
}

案例10-从购物车移除一个商品

需求:在cart.jsp上,点击一个商品的删除,弹出一个提示信息,点击确定,从购物车中移除,否则不删  
步骤分析:  
1.给“删除”添加链接  
2.在cartservlet中编写deleteCart方法  
获取pid  
获取cart,执行remove方法  
重定向到cart.jsp  
Cart.jsp代码
1
2
3
4
5
6
7
8
<td class=”text-center”>
<a href=”javascript:void(0);” onclick=”deleteCartItem(‘${entry.value.product.pid}’)” class=”btn btn-danger delete”>删除</a>
</td>
Function deleteCartItem(pid){
If(confirm(“您确定不要宝宝了吗?亲!”)){
Window.location=”${pageContext.request.contextPath}/cart?method=deleteCartItem&pid=”+pid;
}
}
CartServlet.java代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 删除购物车商品
* @param request
* @param response
* @throws IOException
*/
public void deleteCart(HttpServletRequest request, HttpServletResponse response) throws IOException {
String pid=request.getParameter(“pid”);
HttpSession session = request.getSession();
Cart cart=(cart) session.getAttribute(“cart”);
Map<String,CartItem> cartMap=cart.getCartMap();
If(cartMap.containsKey(pid){
//根据购物车项的pid删除商品
CartItem cartItem =cartMap.get(pid);
cartMap.remove(pid);
//设置购物车删除商品后的价格=总价格-删除商品价格
cart.setTotal(cart.getTotal()-cartItem.getSubToal());
//设置购物车删除后的商品项的集合
cart.setCartMap(cartMap);
session.setAttribute(“cart”,cart);
}
response.sendRedirect(request.getContextPath()+"/cart.jsp");
}

案例11-清空购物车

需求:点击cart.jsp上的清空购物车,需要将购物车所有商品都删除掉  
步骤分析:  
    修改清空购物车的链接  
        /cart?method=cleat  
    编写clear方法  
        获取购物车,执行clearCart方法  
        重定向到cart.jsp  
        判断购物车中是否有商品,  
            有则展示,无则提示  
Cart.jsp部分代码
1
2
3
4
5
6
7
<a href="javascript:void(0);" id="clear" class="clear" onclick="clearCart()">清空购物车</a>

function clearCart(){
if(confirm("您确定要清空购物车吗?")){
window.location = "${pageContext.request.contextPath}/cart?method=clearCart";
}
}
CartServlet.java代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 清空购物车
* @param request
* @param response
* @throws IOException
*/
public void clearCart(HttpServletRequest request, HttpServletResponse response) throws IOException {
/*********清空session中的cart**********/
HttpSession session=request.getSession();
Cart cart=(Cart)session.getAttribute(“cart”);
Map<String,CartItem> cartMap=cart.getCartMap();
cartMap.clear();
cart.setCartMap(cartMap);
session.setAttribute(“cart”,cart);
response.sendRedirect(request.getContextPath()+”/cart.jsp”);
}

案例12-生成订单

需求:在cart.jsp上点击“提交订单”,将购物车的商品保存到数据库中  
实体分析:  
    用户  
    订单  
    商品  
    用户和订单:一对多  
    订单和商品:多对多  
表分析:  
    用户表  
    商品表  
    订单表  

    用户和订单是一对多,在订单表中添加外键  
    订单和商品是多对多,引入一张中间表(orderitem)  

    订单表:  
        Id  
        订单状态  
        订单金额  
        下单时间  
        收货人信息  
        User_id  
    订单项表:  
        Pid  
        Oid  
        Itemid  
        某个商品购买数量  
        小计  
实体具体分析:  
    订单属性:  
        Id  
        订单金额  
        下单时间  
        收货人信息  
        User对象  
        订单项列表  
            List<OrderTiem> list  
    订单项属性:  
        Product对象  
        Order  
        Itemid  
        某个商品的购买数量(count)  
        小计(subtotal)  
步骤分析:
    1.在cart.jsp上,点击提交订单    发送请求  
        路径:/order?method=submitOrder  
    2.编写orderservlet,编写submitOrder方法  
        封装订单对象  
            设置Id  
            设置订单金额  
            设置下单时间  
            设置收货人信息  
            设置User对象  
            设置订单项列表  
                List<OrderTiem> list  
                遍历购物车中购物项,获取每一个购物项  
                封装成orderitem  
                    设置Product对象  
                        购物中获取product  
                    设置Order  
                    设置Itemid  
                        UUIDUtils  
                    设置某个商品的购买数量(count)  
                        购物项中获取  
                    设置小计(subtotal)  
                        购物项中获取  

        调用orderservice,执行保存操作  
        请求转发到订单详情页面  
3.    编写service:    开启事务  
        向orders保存一条  
        向orderitem中保存多条  

案例13-我的订单

需求:在任意页面上,点击“我的订单”,将当前用户的订单(包含订单项列表)分页展示出来  
步骤分析:  
1.修改head.jsp上“我的订单”的连接  
2.在orderservlet中编写findMyOrdersByPage  
获取pagenumber设置pagesize,获取当前用户id  
调用service完成分页查询操作,返回pagebean  
将pagebean放入request域中,请求转发order_list.jsp  
3.service操作  
创建pagebean  
设置总条数  
设置当前页数据  
4.dao操作:  
获取当前页订单数据  
   Sql:只能查询订单的基本信息,没有订单项  
   Select * from orders where uid=? Order by orderitem desc limit ?,?
执行上面的sql,返回的List<Order>遍历orderList集合,获取到每一个订单,关联查询订单项和商品项,将该订单下的所有信息查询出来,封装成orderitem,
将每一个orderitem放入当前order的订单项列表中Select*from orderitem oi,product p where oi.pid=p.pid AND oi.oid=’ 2d6f53ee-c7b3-4836-8d53-e3a0cfcde739’;  
上面的结果用什么封装???  
   使用maplisthandler封装,将查询结果的每一条记录封装成map(key;字段名(和bean属性名一样),value:具体指),
   将所有的map放入list中返回遍历map的list,获取每一个订单的详情,使用beanutils进行封装即可 封装成orderitem和product对象,
 最后将orderitem对象放入,最后将orderitem对象放入订单项列表中[{itemid=xxxx,pname=华为,…},{itemid=yyyy,pname=中兴,…}]  

案例14-订单详情

需求:在订单列表页面上,点击提交订单按钮,展示当前的订单详情
步骤分析:
1.修改提交订单连接
2.在orderservlet编写getById方法
获取oid
调用service查询单个订单 返回值order
将order放入request域中,请求转发到order_info.jsp
3.service操作
4.dao操作
先查询订单信息(没有订单项)
   Select*from orders where oid=?
再查询当前订单的订单项
   Select*from orderitem oi,product p where oi.pid=p.pid and oi.oid=?
使用mapListhandler进行封装
   获取每一个订单项详情,封装成orderitem,最后将orderitem添加到订单的订单项列表即可

文章作者: PanXiaoKang
文章链接: http://example.com/2020/04/15/%E7%94%B5%E5%AD%90%E8%B4%AD%E7%89%A9%E5%95%86%E5%9F%8E%E9%A1%B9%E7%9B%AE/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 向阳榆木
打赏
  • 微信
    微信
  • 支付宝
    支付宝

评论