zoukankan      html  css  js  c++  java
  • javaEE开发案例——购物车

    一、页面

    流程:登录页面(login.jsp)——>购物大厅页面(hall.jsp)——>购物车页面(showMyCart.jsp)——>订单页面(myorder.jsp)——>订单确认页面(orderOK.jsp)

    二、页面+控制

    加上控制逻辑之后:

    登录页面(login.jsp)—>登录控制页面(GoHallUIServlet)—>购物大厅页面(hall.jsp)—>购物控制页面(ShoppingClServlet)—>购物车页面(showMyCart.jsp)—>订单控制页面(GoMyOrderServlet)—>订单页面(myorder.jsp)—>(订单提交处理SubmitOrderServlet)—>订单确认页面(orderOK.jsp)

    三、页面+控制+DAO

    后台数据库,对应四张表:分别是

    用户表uses:(user_id,user_name,user_pwd,user_email,user_tel,user_grade)

    书籍表books:(book_id,book_name,book_price,book_publisher,book_num<库存>)

    订单分为订单表和订单细节表:

    orders(order_id,user_id,order_total<定价总价>,order_time(下订单时间))

    orderdetails(order_id,book_id,book_num)

    对应上述实体表,有对应的Bean,以及各自的service类

     

    package com.bobo.domain;
    
    import java.io.Serializable;
    
    public class BookBean implements Serializable{
        private int book_id;
        private String book_name;
        private int book_price;
        private String book_publisher;
        private int book_num;//库存量
        private int shoping_num=1;//购买量
        
        public int getShoping_num() {
            return shoping_num;
        }
        public void setShoping_num(int shoping_num) {
            this.shoping_num = shoping_num;
        }
        @Override
        public String toString() {
            return "Book [book_id=" + book_id + ", book_name=" + book_name
                    + ", book_price=" + book_price + ", book_publisher="
                    + book_publisher + ", book_num=" + book_num + "]";
        }
        public BookBean(){
            
        }
        
        public BookBean(int book_id, String book_name, int book_price,
                String book_publisher, int book_num) {
            super();
            this.book_id = book_id;
            this.book_name = book_name;
            this.book_price = book_price;
            this.book_publisher = book_publisher;
            this.book_num = book_num;
        }
    
        public int getBook_id() {
            return book_id;
        }
        public void setBook_id(int book_id) {
            this.book_id = book_id;
        }
        public String getBook_name() {
            return book_name;
        }
        public void setBook_name(String book_name) {
            this.book_name = book_name;
        }
        public int getBook_price() {
            return book_price;
        }
        public void setBook_price(int book_price) {
            this.book_price = book_price;
        }
        public String getBook_publisher() {
            return book_publisher;
        }
        public void setBook_publisher(String book_publisher) {
            this.book_publisher = book_publisher;
        }
        public int getBook_num() {
            return book_num;
        }
        public void setBook_num(int book_num) {
            this.book_num = book_num;
        }
        
    
    }
    BookBean

     

    package com.bobo.domain;
    
    import java.io.Serializable;
    
    public class UserBean implements Serializable{
        private int user_id;
        private String user_name;
        private String user_pwd;
        
        public UserBean(){
            
        }
        public UserBean(String user_name, String user_pwd) {
            super();
            this.user_name = user_name;
            this.user_pwd = user_pwd;
        }
        private String user_tel;
        private String user_email;
        private int user_grade;
        @Override
        public String toString() {
            return "User [user_id=" + user_id + ", user_name=" + user_name
                    + ", user_pwd=" + user_pwd + ", user_tel=" + user_tel
                    + ", user_email=" + user_email + ", user_grade=" + user_grade
                    + "]";
        }
        public int getUser_id() {
            return user_id;
        }
        public void setUser_id(int user_id) {
            this.user_id = user_id;
        }
        public String getUser_name() {
            return user_name;
        }
        public void setUser_name(String user_name) {
            this.user_name = user_name;
        }
        public String getUser_pwd() {
            return user_pwd;
        }
        public void setUser_pwd(String user_pwd) {
            this.user_pwd = user_pwd;
        }
        public String getUser_tel() {
            return user_tel;
        }
        public void setUser_tel(String user_tel) {
            this.user_tel = user_tel;
        }
        public String getUser_email() {
            return user_email;
        }
        public void setUser_email(String user_email) {
            this.user_email = user_email;
        }
        public int getUser_grade() {
            return user_grade;
        }
        public void setUser_grade(int user_grade) {
            this.user_grade = user_grade;
        }
        
        
    
    }
    UserBean
    package com.bobo.service;
    
    import com.bobo.domain.BookBean;
    import com.bobo.utils.SqlHelper;
    
    import java.util.ArrayList;
    
    public class BookService {
        /**
         * 根据id返回对应的书籍
         * @param id 书籍id
         * @return
         */
        public BookBean getBookById(int id) {
            String sqltext = "select * from books where book_id=?";
            String[] params = { id + "" };
            try {
                ArrayList<Object[]> sqlResult = SqlHelper.ExecuteReader(sqltext,
                        params);
                if (sqlResult.size() == 1) {
                    Object[] currentRow = sqlResult.get(0);
                    BookBean book = new BookBean(Integer.parseInt(currentRow[0]
                            + ""), currentRow[1] + "",
                            Integer.parseInt(currentRow[2] + ""), currentRow[3]
                                    + "", Integer.parseInt(currentRow[4] + ""));
                    return book;
    
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }
            return null;
    
        }
         
        
    
        public ArrayList<BookBean> getAllBooks() {
            ArrayList<BookBean> books = new ArrayList<BookBean>();
            String sqlText = "select * from books";
            try {
                ArrayList<Object[]> sqlResult = SqlHelper.ExecuteReader(sqlText,
                        null);
                Object[] currentRow = null;
                for (int i = 0; i < sqlResult.size(); i++) {
                    currentRow = sqlResult.get(i);
    
                    BookBean book = new BookBean(Integer.parseInt(currentRow[0]
                            + ""), currentRow[1] + "",
                            Integer.parseInt(currentRow[2] + ""), currentRow[3]
                                    + "", Integer.parseInt(currentRow[4] + ""));
                    books.add(book);
    
                }
                return books;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }
    
        }
    
    }
    BookService
    package com.bobo.service;
    
    import java.util.ArrayList;
    
    import com.bobo.domain.UserBean;
    import com.bobo.utils.SqlHelper;
    
    //处理和user表相关的业务逻辑
    public class UserService {
        /**
         * 检查该用户是否存在,如果存在,返回true,否则返回false
         * @param user 传入的用户对象,同时也通过参数传递,返回用户的其他相关信息
         * @return
         */
        public boolean checkUser(UserBean user){
            String sqlText="select * from users where user_name=? and user_pwd=?";
            String[] params={user.getUser_name(),user.getUser_pwd()};
            ArrayList<Object[]> result;
            try {
                result = SqlHelper.ExecuteReader(sqlText, params);
                if(result==null || result.size()==0){
                    return false;
                    
                }else{
                    //通过参数来进行传递
                    Object[] temp=result.get(0);
                     user.setUser_id(Integer.parseInt(temp[0]+""));
                     user.setUser_name(temp[1]+"");
                     user.setUser_pwd(temp[2]+"");
                     user.setUser_email(temp[3]+"");
                     user.setUser_tel(temp[4]+"");
                     user.setUser_grade(Integer.parseInt(temp[5]+""));
                     return true;
                    
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return false;
            }
            
            
        }
    }
    UserService
    package com.bobo.service;
    import com.bobo.utils.DateHelper;
    import com.bobo.utils.SqlHelper;
    import com.bobo.domain.BookBean;
    import com.bobo.domain.UserBean;
    
    public class OrderService {
        private DateHelper dateHelper=new DateHelper();
     
        /*
         * 处理提价订单的业务逻辑
         */
        public void submitOrder(ShopingCart myCart,UserBean user){
            String dateTime=dateHelper.getCurrentTime();
            String sqlText="insert into orders (user_id,order_total,order_time) values(?,?,?)";
            String[] params={user.getUser_id()+"",myCart.getTotalPrice()+"",dateTime};
            try {
                int key=SqlHelper.ExecuteInsertReturnKey(sqlText, params);
                System.out.println("插入记录的key值是"+key);
                for(int i=0;i<myCart.getCartBooks().size();i++){
                    BookBean book=myCart.getCartBooks().get(i);
                    sqlText="insert into orderDetails (order_id,book_id,shopping_num,order_price) values (?,?,?,?)";
                    int price=book.getBook_price()*book.getShoping_num();
                    String[] pars={key+"",book.getBook_id()+"",book.getShoping_num()+"", price+""};
                    //这种每一次插入都需要连接打开和关闭,显然是不太好的
                    SqlHelper.ExecuteNonQuery(sqlText, pars);
                } 
            } catch (Exception e) {
                 
                e.printStackTrace();
            }
        }
    
    }
    orderService

    除了上述实体表对应的bean和Service之外,还有一个内存中的实体对象:购物车;数据库中并没有购物车这张表,而是利用内存中的一个hashmap来实现

    package com.bobo.service;
    import com.bobo.domain.*;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    
    //代表我的购物车
    //在本案例中,购物车对应内存中的hashmap,而非一张实际表
    
    public class ShopingCart {
            HashMap<Integer,BookBean> cart=new HashMap<Integer,BookBean>();
    
            public void addBook(Integer id){
                
                if(cart.containsKey(id)){
                    BookBean book=cart.get(id);
                    int num=book.getShoping_num();
                    book.setShoping_num(num+1);
                    cart.put(id, book);
                }else{
                    BookBean book=new BookService().getBookById(id);
                    cart.put(id, book);                
                }
                
            }
            /*//添加书
            public void addBook(Integer id,BookBean book){
                if(cart.containsKey(id)){
                    int num=book.getShoping_num();
                    book.setShoping_num(num+1);
                    cart.put(id, book);
                }else{
                    cart.put(id, book);
                    
                }
            }*/
            @Override
            public String toString() {
                String result="";
                for(int i=0;i<cart.size();i++){
                    result+="book"+i+":"+cart.get(i).toString()+";";
                }
                return result;
            }
            //删除书
            public void delBook(Integer id ){
                int temp=cart.get(id).getShoping_num();
                if(temp<=1){
                    cart.remove(id);
                }else{
                    cart.get(id).setShoping_num(temp-1);
                }
                
            }
            //清空书
            public void clearCart(){
                cart.clear();
            } 
            //更新某本书的数量
            public void updateBook(int book_id,int book_num){
                BookBean book=cart.get(book_id);
                book.setShoping_num(book_num);
                
                
            }
            //得到购物车中的所有书
            public ArrayList<BookBean> getCartBooks(){
                ArrayList<BookBean> result=new ArrayList<BookBean>();
                for(Integer id:cart.keySet()){
                    result.add(cart.get(id));
                }
                return result;
            }
            
            //获取购物车中物品的总价
            public int getTotalPrice(){
                int result=0;
                for(int id :cart.keySet()){
                    result+=cart.get(id).getBook_price()*cart.get(id).getShoping_num();
                    
                }
                return result;
            }
    
    }
    ShopingCart

    四、顺着页面流和处理逻辑,来看一下整个工程吧

      r

    整个工程的结构如上图所示,其中所有的jsp文件都放置在WEB-INF目录下,放置暴露给用户,仅在根目录下放置一个index.jsp作为入口,其核心是依旧jsp:forward语句,

    1)具体如下:

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    
    <!DOCTYPE >
    <html lang="zh-hans">
    <head> 
    <meta charset="utf-8">
    <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="lib/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="lib/bootstrap/css/animate.min.css">
    <link rel="stylesheet" href="css/login.css">
    <title>用户登录页面</title>
    </head>
      
      <body>
         <jsp:forward page="/WEB-INF/login.jsp"></jsp:forward>
      </body>
    </html>
    index.jsp

    2)上述forward语句,将工程转到登录页面login.jsp内容如下 

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    
    
    <!DOCTYPE >
    <html lang="zh-hans">
    <head>
    <meta charset="utf-8"> 
    <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="mylib/bootstrap/css/bootstrap.min.css">
     
    <link rel="stylesheet" href="css/login.css">
    <title>用户登录页面</title>
    </head>
    
    <body>
         
        <div class="login_div">
            <h1 class="text-center">用户登录</h1>
            <form class="form-horizontal" role="form" method="post" action="/Myshoping/GoHallUI">
                <div class="form-group">
                    <label for="firstname" class="col-sm-2 control-label">用户名</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" name="username"
                            placeholder="请输入用户名">
                    </div>
                </div>
                <div class="form-group">
                    <label for="lastname" class="col-sm-2 control-label">密码</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" name="password"
                            placeholder="请输入密码">
                    </div>
                </div>             
                <div class="form-group">
                    <div class="row">
                    <div class="col-sm-offset-1 col-sm-5">
                        <button type="submit" class="btn btn-default" id="btn_button">登录</button>
                    </div>
                    <div class="col-sm-offset-1 col-sm-5">
                        <button type="submit" class="btn btn-default" id="btn_button">登录</button>
                    </div>
                    </div>
                </div>
            </form>
        </div>
    
    </body>
    </html>
    login.jsp

    login.jsp呈现登录表单,要求用户输入用户名和密码

     3)用户如果合法,下一步将跳转到购物大厅页面(hall.jsp),其中,对用户身份的验证将由GoHallUIServlet来完成

    package com.bobo.controller;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.bobo.domain.BookBean;
    import com.bobo.domain.UserBean;
    import com.bobo.service.BookService;
    import com.bobo.service.ShopingCart;
    import com.bobo.service.UserService;
    
    public class GoHallUI extends HttpServlet {
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            //判断用户是否已经登录(用户可能登录后,从其他页面进入购物大厅)
            if(request.getSession().getAttribute("loginUser")!=null){
                //说明用户已经登录过了,此时就不用为用户新建购物车了
                System.out.println("说明用户已经登录过了,此时就不用为用户新建购物车了");
                BookService bookService=new BookService();
                ArrayList<BookBean> bookList=bookService.getAllBooks();
                request.setAttribute("books",bookList );
                request.getRequestDispatcher("/WEB-INF/hall.jsp").forward(request, response);
                return;
            }
            //获得从登陆页面传递的用户名和密码
            String user_name=request.getParameter("username");
            String user_pwd=request.getParameter("password");
            UserBean login_user=new UserBean(user_name,user_pwd);
            //第一次成功登陆后,将用户放置到session中
            request.getSession().setAttribute("loginUser", login_user);
            UserService userService=new UserService();
            if(userService.checkUser(login_user)){
                //如果用户合法,那么跳转到购物大厅
                //用户登录成功后,为其创建购物车
                System.out.println("用户首次合法登录");
                ShopingCart cart=new ShopingCart();
                request.getSession().setAttribute("cart", cart);
                //同时为购物大厅准备好书籍数据(之所以这么设计,是为了保证如果用户不经过登录直接跳转到购物大厅,是看不到任何数据的)
                BookService bookService=new BookService();
                ArrayList<BookBean> bookList=bookService.getAllBooks();
                request.setAttribute("books",bookList );
                request.getRequestDispatcher("/WEB-INF/hall.jsp").forward(request, response);
            }else{
                //如果不合法,返回登陆页面
                System.out.println("用户非法登录");
                request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
                
            }
            
            
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doGet(request,response);
        }
    
    }
    GoHallUIServlet

    GoHallUIServlet主要完成以下工作:

    a.如果是由登录页面跳转来的,验证用户的身份合法性(如果合法,那么将用户信息放置到session中,同时为用户创建一个购物车,将其也放置到session中)

    b.如果是有其他页面想要跳转至购物大厅,那么检验session中是否有此用户信息

    c.准备购物大厅要呈现的书籍数据

    4)购物大厅页面,向用户呈现书籍信息,并提供购买入口

     

    <%@ page language="java"
        import="java.util.*,java.util.ArrayList,com.bobo.domain.BookBean "
        pageEncoding="utf-8"%>
    
    
    <!DOCTYPE >
    <html lang="zh-hans">
    <head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="mylib/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/hall.css">
    <title>购物大厅</title>
    </head>
    
    <body>
        <div class="container">
            <h1 class="text-center">欢迎进入购物大厅</h1>
            <table>
                <%
                    ArrayList<BookBean> books = (ArrayList<BookBean>) request
                            .getAttribute("books");
                %>
                <tr>
                    <td>书名</td>
                    <td>价格</td>
                    <td>出版社</td>
                    <td>点击购买</td>
                </tr>
                <%
                    for (int i = 0; i < books.size(); i++) {
                    
                %>
                <tr>
                    <td><%=books.get(i).getBook_name()%></td>
                    <td><%=books.get(i).getBook_price()%></td>
                    <td><%=books.get(i).getBook_publisher()%></td>
                    <td><a href="/Myshoping/ShoppingClServlet?type=add&id=<%=books.get(i).getBook_id()%>">购买</a></td>
                </tr>
                <%
                    }
                %>
            </table>
            <div>
                <button type="button" id="showCart">查看购物车</button>
                <a href="/Myshoping/index.jsp">返回重新登录</a>
            </div>
        </div>
    
    
    </body>
    </html>
    hall.jsp

     5)用户的购买行为记录在购物车中(这不是一个数据库中的对象,用一个内存中hashmap来表示);用户在hall.jsp页面的购买请求,经过ShopingClServlet处理之后,在跳转至购物车页面(用户操作购物车的行为可能有多种,因此使用额外的参数type来记录究竟是哪一种行为)

    package com.bobo.controller;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.bobo.service.BookService;
    import com.bobo.service.ShopingCart;
    
    //该控制器用于响应用户购买商品的请求
    public class ShoppingClServlet extends HttpServlet {
    
        /**
         * The doGet method of the servlet. <br>
         * 
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request
         *            the request send by the client to the server
         * @param response
         *            the response send by the server to the client
         * @throws ServletException
         *             if an error occurred
         * @throws IOException
         *             if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            doPost(request, response);
        }
    
        /**
         * The doPost method of the servlet. <br>
         * 
         * This method is called when a form has its tag value method equals to
         * post.
         * 
         * @param request
         *            the request send by the client to the server
         * @param response
         *            the response send by the server to the client
         * @throws ServletException
         *             if an error occurred
         * @throws IOException
         *             if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            ShopingCart cart = (ShopingCart) request.getSession().getAttribute(
                    "cart");
            String type = request.getParameter("type");
            if (type.equals("add")) {
                // 从购物大厅页面接受用户的购买请求,准备数据,跳转到购物车页面
                int book_id = Integer.parseInt(request.getParameter("id"));
                cart.addBook(book_id);            
                
            } else if (type.equals("delete")) {
                // 从购物车页面接受用户的删除请求,准备数据,再跳转到购物车页面,但是怎么判断是从哪个页面跳转来的呢
                int del_id = Integer.parseInt(request.getParameter("del_id"));
                System.out.println(del_id);
                cart.delBook(del_id);
            }else if(type.equals("update")){
                //如果是数量的更新操作,注意每一行都有一个id和对应的数量,因此获得的是一个数组
                String[] book_ids=request.getParameterValues("id");
                String[] book_nums=request.getParameterValues("book_num");    
                 
                //去购物车业务类中进行更新
                for(int i=0;i<book_ids.length;i++){
                    cart.updateBook(Integer.parseInt(book_ids[i]), Integer.parseInt(book_nums[i]));
                }
                 
                
            }
            request.setAttribute("totalPrice", cart.getTotalPrice());
            request.setAttribute("cartBooks", cart.getCartBooks());
            System.out.println(cart.getCartBooks());
            request.getRequestDispatcher("/WEB-INF/showMyCart.jsp").forward(
                    request, response);
                 
    
        }
    
    }
    shopingClServlet

     该页面的处理用户对于购物车的各种行为,包括购买,删除和数量更新,处理之后,跳转好购物车页面showMyCart.jsp

    6)在showMyCart.jsp中,用户可以对购物车中的书籍进行删除和数量更新,这些请求,也将由shopingClServlet来处理

    <%@ page language="java" import="java.util.*,com.bobo.domain.BookBean"
        pageEncoding="utf-8"%>
    
    
    <!DOCTYPE >
    <html lang="zh-hans">
    <head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="mylib/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/showMyCart.css">
    <title>我的购物车</title>
    </head>
    
    <body>
        <div class="container">
            <h1 class="text-center">我的购物车</h1>
            <form action="ShoppingClServlet?type=update" method="post">
                <table>
                    <tr>
                        <td>book_id</td>
                        <td>书名</td>
                        <td>价格</td>
                        <td>出版社</td>
                        <td>数量</td>
                        <td>删除</td>
                    </tr>
                    <%
                        ArrayList<BookBean> list = (ArrayList<BookBean>) request
                                .getAttribute("cartBooks");
                        for(int i=0;i<list.size();i++){
                        BookBean book=list.get(i);
                    %>
                    <tr>
                        <!-- 使用隐藏的表单来传递内容 -->
                        <td><%=book.getBook_id() %><input type="hidden" value=<%=book.getBook_id() %> name="id"></td>
                        <td><%=book.getBook_name() %></td>
                        <td><%=book.getBook_price()%></td>
                        <td><%=book.getBook_publisher()%></td>
                        <td><input type="text" name="book_num" value=<%=book.getShoping_num() %>></input></td>
                        <td><a href="/Myshoping/ShoppingClServlet?type=delete&del_id=<%=book.getBook_id()%>">删除</a></td>
                    </tr>
                    <%} %>
                    <tr>
                        <td colspan="6"><input type="submit" value="update"/></td>
                    </tr>
                </table>
                </form>
                <div>
                    <p>商品总价是: ${totalPrice} 元</p>
                </div>
                <p>
                    <a href="/Myshoping/GoMyOrder">提交订单</a>            
                    <a href="/Myshoping/GoHallUI">返回购物大厅</a>
                </p>
            </form>
        </div>
    
    
    </body>
    </html>
    showMyCart.jsp

    7)最终,如果用户确定购买,点击购物车页面“确认订单”页面后,将由GoMyOrderServlet将订单信息记录到数据库中,然后跳转至订单成功页面

    package com.bobo.controller;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.bobo.domain.BookBean;
    import com.bobo.domain.UserBean;
    import com.bobo.service.ShopingCart;
    //处理用户查看订单的请求
    public class GoMyOrder extends HttpServlet {
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            //为订单查看页面准备用户信息,和订单信息
            ShopingCart cart=(ShopingCart) request.getSession().getAttribute("cart");        
            ArrayList<BookBean> books=cart.getCartBooks();
            request.setAttribute("books", books);
            int total_price=cart.getTotalPrice();
            request.setAttribute("total_price", total_price);
            UserBean user=(UserBean)request.getSession().getAttribute("loginUser");
            request.setAttribute("loginUser", user);
            request.getRequestDispatcher("/WEB-INF/myOrder.jsp").forward(request, response);
            
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
             doGet(request,response);
        }
    
    }
    GoMyOrderServlet

     订单的插入操作涉及两张表,订单表和订单详情表,其中要注意,在向订单表中插入一条新订单,数据库自动生成一条订单id后,在向订单详情表中插入详情后,这里的订单id一定要是上面生成的id,因此要注意数据库操作的事务性。

     8)最终的订单ok页面(邮件的发送暂时没有做)

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    
    
    <title>订单已提交</title>
    
    <meta charset="utf-8">
    <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    
    </head>
    
    <body>
        <h2>订单已经提交,邮件已发送至您的注册邮箱,请至邮箱确认!</h2>      
    </body>
    </html>
    OrderOK.jsp

     其他:此外,该项目中,自己实现了两个listener

    1)ServletContextEvent

    在本例中的功能是每隔一段时间打印一段日志,在实际项目中,可以用于应用启动的时候获取数据库的参数,以及定时备份等

    package com.bobo.listener;
    
    import javax.servlet.ServletContextEvent;
    import java.util.Timer;
    import java.util.TimerTask;
    
    import javax.servlet.ServletContextListener;
    /*
     * 这个类用于监听整个web应用的启动和销毁,可以用于执行某些定时程序,获得数据库的连接等,有点类似于on-start:1的servlet
     * */
    
    public class ContextListener implements ServletContextListener {
    private Timer timer;
        @Override
        public void contextDestroyed(ServletContextEvent arg0) {
            timer.cancel();
            
        }
    
        @Override
        public void contextInitialized(ServletContextEvent arg0) {
            // TODO Auto-generated method stub
            
             timer=new Timer();
                timer.schedule(new TimerTask(){
    
                    @Override
                    public void run() {
                        System.out.println("定时器正常工作");
                        
                    }
                    
                }, 3*60);
        }
    
    }
    ServletContextEvent

     

    1)ServletContextEvent

    在本例中的功能是每隔一段时间打印一段日志,在实际项目中,可以用于应用启动的时候获取数据库的参数,以及定时

     

     

     

  • 相关阅读:
    POJ 2418 Hardwood Species(STL在map应用)
    在反思性学习
    孙陪你,了解它的权力--Kinect结合的发展Unity3D游戏应用开发
    python在windows通过安装模块错误
    Linux怪哉ntfs
    Js 表单序列化
    微信开发
    Ecshop开发
    FTP配置和用户设置权限
    wget
  • 原文地址:https://www.cnblogs.com/bobodeboke/p/4602427.html
Copyright © 2011-2022 走看看