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

在本例中的功能是每隔一段時間打印一段日志,在實際項目中,可以用於應用啟動的時候獲取數據庫的參數,以及定時

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM