Java EE development case shopping cart

1, Page

Process: login page( login.jsp )- > shopping hall page( hall.jsp )- > shopping cart page( showMyCart.jsp )- > order page( myorder.jsp )Order confirmation page( orderOK.jsp)

2, Page + control

After adding control logic:

Login page( login.jsp )- > login control page (GoHallUIServlet) - > shopping hall page( hall.jsp )- > shopping control page (ShoppingClServlet) - > shopping cart page( showMyCart.jsp )- > order control page (gomyordservlet) - > order page( myorder.jsp )- > (order submission processing submitorservlet) - > order confirmation page( orderOK.jsp)

3, Page + control + DAO

Background database, corresponding to four tables: respectively

Users table uses: (user_id,user_name,user_pwd,user_email,user_tel,user_grade)

books: (Book_ id,book_ name,book_ price,book_ publisher,book_ Num < stock >)

Orders are divided into order form and order detail form:

orders(order_ id,user_ id,order_ Total < total pricing price >, order_ Time (order placement time))

orderdetails(order_id,book_id,book_num)

Corresponding to the above entity table, there are corresponding beans and their respective service classes

 

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;//Inventory
    private int shoping_num=1;//Purchase volume
    
    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 {
    /**
     * Return the corresponding book according to the id
     * @param id Book 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;

//Handling and user Table related business logic
public class UserService {
    /**
     * Check whether the user exists. If so, return true. Otherwise, return false
     * @param user The user object passed in also returns other relevant information of the user through parameter passing
     * @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{
                //Pass through parameters
                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();
 
    /*
     * Business logic for handling price increase orders
     */
    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("Insert recorded key The value is"+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+""};
                //This kind of connection needs to be opened and closed every time it is inserted, which is obviously not good
                SqlHelper.ExecuteNonQuery(sqlText, pars);
            } 
        } catch (Exception e) {
             
            e.printStackTrace();
        }
    }

}
orderService

In addition to the bean s and services corresponding to the above entity table, there is also an entity object in memory: shopping cart. There is no shopping cart table in the database, but it is implemented by using a hashmap in memory

package com.bobo.service;
import com.bobo.domain.*;

import java.util.ArrayList;
import java.util.HashMap;

//On behalf of my shopping cart
//In this case, the shopping cart corresponds to the hashmap,Not a physical table

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);                
            }
            
        }
        /*//Add 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;
        }
        //Delete book
        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);
            }
            
        }
        //Empty book
        public void clearCart(){
            cart.clear();
        } 
        //Update the number of a Book
        public void updateBook(int book_id,int book_num){
            BookBean book=cart.get(book_id);
            book.setShoping_num(book_num);
            
            
        }
        //Get all the books in the shopping cart
        public ArrayList<BookBean> getCartBooks(){
            ArrayList<BookBean> result=new ArrayList<BookBean>();
            for(Integer id:cart.keySet()){
                result.add(cart.get(id));
            }
            return result;
        }
        
        //Get the total price of items in the cart
        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

4, Follow the page flow and processing logic to see the whole project

  r

The structure of the whole project is shown in the figure above. All JSP files are placed in the WEB-INF directory and exposed to the user. Only one is placed in the root directory index.jsp As an entrance, its core is still jsp:forward sentence,

1) The details are as follows:

<%@ 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>User login page</title>
</head>
  
  <body>
     <jsp:forward page="/WEB-INF/login.jsp"></jsp:forward>
  </body>
</html>
index.jsp

2) The forward statement above will take the project to the login page login.jsp The content is as follows

<%@ 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>User login page</title>
</head>

<body>
     
    <div class="login_div">
        <h1 class="text-center">User login</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">user name</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="username"
                        placeholder="enter one user name">
                </div>
            </div>
            <div class="form-group">
                <label for="lastname" class="col-sm-2 control-label">password</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="password"
                        placeholder="Please input a password">
                </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">Sign in</button>
                </div>
                <div class="col-sm-offset-1 col-sm-5">
                    <button type="submit" class="btn btn-default" id="btn_button">Sign in</button>
                </div>
                </div>
            </div>
        </form>
    </div>

</body>
</html>
login.jsp

login.jsp Presents a login form that requires the user to enter a user name and password

3) if the user is legal, the next step is to jump to the shopping hall page( hall.jsp ), where authentication of user identity will be done by 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");
        //Judge whether the user has logged in (after the user may log in, enter the shopping hall from other pages)
        if(request.getSession().getAttribute("loginUser")!=null){
            //Indicates that the user has logged in,At this time, there is no need to create a new shopping cart for users
            System.out.println("Indicates that the user has logged in,At this time, there is no need to create a new shopping cart for users");
            BookService bookService=new BookService();
            ArrayList<BookBean> bookList=bookService.getAllBooks();
            request.setAttribute("books",bookList );
            request.getRequestDispatcher("/WEB-INF/hall.jsp").forward(request, response);
            return;
        }
        //Get the user name and password passed from the login page
        String user_name=request.getParameter("username");
        String user_pwd=request.getParameter("password");
        UserBean login_user=new UserBean(user_name,user_pwd);
        //After the first successful login, place the user in the session in
        request.getSession().setAttribute("loginUser", login_user);
        UserService userService=new UserService();
        if(userService.checkUser(login_user)){
            //If the user is legal, jump to the shopping hall
            //After the user logs in successfully, create a shopping cart for him / her
            System.out.println("First legal login");
            ShopingCart cart=new ShopingCart();
            request.getSession().setAttribute("cart", cart);
            //At the same time, prepare book data for the shopping hall (so designed to ensure that if users jump to the shopping hall without login, they will not see any data)
            BookService bookService=new BookService();
            ArrayList<BookBean> bookList=bookService.getAllBooks();
            request.setAttribute("books",bookList );
            request.getRequestDispatcher("/WEB-INF/hall.jsp").forward(request, response);
        }else{
            //If not, return to the landing page
            System.out.println("Illegal user login");
            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 mainly completes the following work:

a. If it's from the login page, verify the user's identity and legitimacy (if it's legal, put the user information into the session, create a shopping cart for the user, and put it into the session as well)

b. If there are other pages that want to jump to the shopping hall, check whether there is this user information in the session

c. Prepare the book data to be presented in the shopping hall

4) Shopping hall page, presenting book information to users and providing purchase access

 

<%@ 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>Shopping hall</title>
</head>

<body>
    <div class="container">
        <h1 class="text-center">Welcome to the shopping hall</h1>
        <table>
            <%
                ArrayList<BookBean> books = (ArrayList<BookBean>) request
                        .getAttribute("books");
            %>
            <tr>
                <td>title</td>
                <td>Price</td>
                <td>press</td>
                <td>Click to buy</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()%>">purchase</a></td>
            </tr>
            <%
                }
            %>
        </table>
        <div>
            <button type="button" id="showCart">View Cart</button>
            <a href="/Myshoping/index.jsp">Return to log in again</a>
        </div>
    </div>


</body>
</html>
hall.jsp

5) the user's purchase behavior is recorded in the shopping cart (this is not an object in a database, which is represented by a hashmap in memory); the user's purchase behavior is recorded in the shopping cart hall.jsp After the purchase request of the page is processed by ShopingClServlet, it will jump to the shopping cart page (there may be many behaviors for the user to operate the shopping cart, so the extra parameter type is used to record which kind of line it is For)

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;

//This controller is used to respond to the user's purchase request
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")) {
            // Accept the user's purchase request from the shopping hall page, prepare the data and jump to the shopping cart page
            int book_id = Integer.parseInt(request.getParameter("id"));
            cart.addBook(book_id);            
            
        } else if (type.equals("delete")) {
            // Accept the user's delete request from the shopping cart page, prepare the data, and then jump to the shopping cart page,But how to judge which page to jump from
            int del_id = Integer.parseInt(request.getParameter("del_id"));
            System.out.println(del_id);
            cart.delBook(del_id);
        }else if(type.equals("update")){
            //If it is a quantity update operation, note that there is one for each line id And the corresponding number, so you get an array
            String[] book_ids=request.getParameterValues("id");
            String[] book_nums=request.getParameterValues("book_num");    
             
            //Update in shopping cart business category
            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

This page deals with various behaviors of users for shopping cart, including purchase, deletion and quantity update. After processing, jump to the shopping cart page showMyCart.jsp

6) At showMyCart.jsp The user can delete and update the number of books in the shopping cart. These requests will also be handled by 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>My shopping cart</title>
</head>

<body>
    <div class="container">
        <h1 class="text-center">My shopping cart</h1>
        <form action="ShoppingClServlet?type=update" method="post">
            <table>
                <tr>
                    <td>book_id</td>
                    <td>title</td>
                    <td>Price</td>
                    <td>press</td>
                    <td>number</td>
                    <td>delete</td>
                </tr>
                <%
                    ArrayList<BookBean> list = (ArrayList<BookBean>) request
                            .getAttribute("cartBooks");
                    for(int i=0;i<list.size();i++){
                    BookBean book=list.get(i);
                %>
                <tr>
                    <!-- Use hidden forms to pass content -->
                    <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()%>">delete</a></td>
                </tr>
                <%} %>
                <tr>
                    <td colspan="6"><input type="submit" value="update"/></td>
                </tr>
            </table>
            </form>
            <div>
                <p>The total price of the goods is: ${totalPrice} element</p>
            </div>
            <p>
                <a href="/Myshoping/GoMyOrder">place order</a>            
                <a href="/Myshoping/GoHallUI">Back to shopping hall</a>
            </p>
        </form>
    </div>


</body>
</html>
showMyCart.jsp

7) Finally, if the user decides to purchase, click the "confirm order" page on the shopping cart page, the order information will be recorded in the database by the gomyordservlet, and then jump to the order success page

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;
//Process the user's request to view the order
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();
        //Prepare user information and order information for order view page
        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

The order insertion involves two tables, order table and order detail table. Note that after inserting a new order into the order table, the database automatically generates an order id. after inserting details into the order detail table, the order id here must be the id generated above, so pay attention to the transactional nature of the database operation.

8) final order ok page (email is not sent yet)

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>


<title>Order submitted</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>The order has been submitted and the email has been sent to your registered email. Please confirm it at the email!</h2>      
</body>
</html>
OrderOK.jsp

 

Other: in addition, in this project, two listener s have been implemented

1)ServletContextEvent

In this example, the function is to print a log every other period of time. In the actual project, it can be used to obtain the parameters of the database when the application is started, as well as timing backup, etc

 

package com.bobo.listener;

import javax.servlet.ServletContextEvent;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContextListener;
/*
 * This class is used to monitor the start-up and destruction of the entire web application. It can be used to execute certain timing programs, obtain database connections, etc., which is similar to on-start:1 servlet for
 * */

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("Timer works normally");
                    
                }
                
            }, 3*60);
    }

}
ServletContextEvent

 

 

1)ServletContextEvent

The function in this example is to print a log every other period of time. In the actual project, it can be used to obtain the database parameters and timing when the application starts

Tags: JSP Java Database IE

Posted on Sun, 24 May 2020 02:39:30 -0400 by taps128