Java(五)線上點餐系統

線上點餐系統

目錄

線上點餐系統

步驟一:搭建開發環境

步驟二:SQLServer資料庫設計

FoodInfo:

FoodOrderInfo:

OrderInfo:

UserInfo:

Java中對資料庫的連線

步驟三:程式_JavaBean

實體類FoodInfo:

實體類FoodOrderInfo:

實體類Item:

實體類UserInfo:

步驟四:程式_ Dao

步驟五:程式_ Servlet

步驟六:Web層_JSP

實驗結果

效果一: 實現商家和使用者兩種角色的註冊與登入

效果二: 使用者名稱存入cookie並顯示在頁面上

效果三: 選某一件菜品,選好之後提交

效果四: 使用socket通訊

附加效果五: 一次提交多件菜品

附加效果六:檢視訂單歷史

原始碼:

總結:


 

步驟一:搭建開發環境

Tomcat8的安裝配置

配置測試結果截圖:開啟D:\java\TOMCAT8\bin,注意安裝的TOMCAT8與jre放在同一資料夾下,先開啟tomcat8w,再開啟tomcat,再將tomcat8w關閉,執行測試。

 

步驟二:SQLServer資料庫設計

建立資料庫WubifenDatabase,裡面建立foodInfo、foodOrderInfo、orderInfo、userInfo四張表。.

表頭分別(測試資料已存入資料庫):

FoodInfo:

FoodOrderInfo:

OrderInfo:

UserInfo:

為了連線方便,我使用SQL身份預設sa使用者連線,安全起見,給資料庫伺服器設定了訪問密碼:970000

 

Java中對資料庫的連線

程式碼如下:

package com.sxdx.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BaseDAO {
       public static Connection getConn()
       {
              Connection conn=null;
              try {
                     Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                     conn=DriverManager.getConnection("jdbc:sqlserver://localhost;databasename=WubifenDatabase","sa","970000");
              } catch (Exception e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                     System.out.printf("沒連上資料庫");
              }
              return conn;
       }
       public static void closeAll(Connection conn,PreparedStatement ps,ResultSet rs)
       {
              if(rs!=null)
              {
                     try {
                            rs.close();
                     } catch (SQLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                     }
              }
              if(ps!=null)
              {
                     try {
                            ps.close();
                     } catch (SQLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                     }
              }
              if(conn!=null)
              {
                     try {
                            conn.close();
                     } catch (SQLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                     }
              }
       }
}

步驟三:程式_JavaBean

實體類FoodInfo:

package com.sxdx.vo;
public class FoodInfo {
    private String foodID;
    private String foodName;   
    private String remark;
    private double foodPrice;  
    private String description;
    private String foodImage;
    public String getFoodID() {
        return foodID;
    }
    public void setFoodID(String foodID) {
        this.foodID = foodID;
    }
    public String getFoodName() {
        return foodName;
    }
    public void setFoodName(String foodName) {
        this.foodName = foodName;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    public double getFoodPrice() {
        return foodPrice;
    }
    public void setFoodPrice(double foodPrice) {
        this.foodPrice = foodPrice;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public String getFoodImage() {
        return foodImage;
    }
    public void setFoodImage(String foodImage) {
        this.foodImage = foodImage;
    }  
           
}

實體類FoodOrderInfo:

package com.sxdx.vo;
public class FoodOrderInfo {
    private String customerName;
    private String address;
    private String telephone;
    private double totalPrice;
    private String state;
    public String getCustomerName() {
        return customerName;
    }
    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    public double getTotalPrice() {
        return totalPrice;
    }
    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }
    public String getstate() {
        return state;
    }
    public void setstate(String state) {
        this.state = state;
    }
    public FoodOrderInfo(String customerName, String address,
             String telephone, double totalPrice, String state) {
        super();//用super操作被隱藏的成員變數和方法/使用super呼叫父類的構造方法
        this.customerName = customerName;
        this.address = address;
        this.telephone = telephone;
        this.totalPrice = totalPrice;
        this.state= state;
    }
}

實體類Item:

package com.sxdx.vo;
public class Item {
    private FoodInfo foodInfo;
    private int count;
    public FoodInfo getFoodInfo() {
        return foodInfo;
    }
    public void setFoodInfo(FoodInfo foodInfo) {
        this.foodInfo = foodInfo;
    }
    public int getCount() {
        return count;
    }
    public void setCount(int count) {
        this.count = count;
    }
   
}

實體類UserInfo:

package com.sxdx.vo;
public class UserInfo {
    private String loginName;
    private String loginPass;
    public String getLoginName() {
        return loginName;
    }
    public void setLoginName(String loginName) {
        this.loginName = loginName;
    }
    public String getLoginPass() {
        return loginPass;
    }
    public void setLoginPass(String loginPass) {
        this.loginPass = loginPass;
    }
}

 

 

步驟四:程式_ Dao

擷取部分:顧客/商家

UserInfoDAO:

package com.sxdx.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.http.Cookie;
public class UserInfoDAO {
    //驗證使用者是否成功登入
    public int checkLogin(String username,String userpass)
    {
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        int result=0;
        try
        {
            conn=BaseDAO.getConn();
            ps=conn.prepareStatement("select * from userinfo where loginname=? and loginpass=?");
            ps.setString(1, username);
            ps.setString(2, userpass);
            rs=ps.executeQuery();
            if(rs.next())
            {
                String str1="customer";
                String str2="business";
                if(str1.equals(rs.getString("Permission")))
                result=1;
                else if(str2.equals(rs.getString("Permission")))
                result=2;
            }
        }catch(Exception ex)
        {
            ex.printStackTrace();
        }finally
        {
            BaseDAO.closeAll(conn, ps, rs);
        }
        return result;
    }
    public boolean insertUser(String username,String userpass) {
        Connection conn=null;
        PreparedStatement ps=null;
        int rs=0;
        boolean flag=false;
        try {
        conn=BaseDAO.getConn();
        ps=conn.prepareStatement( "insert into userInfo (loginName,loginPass,Permission) values(?,?,?)");
        ps.setString(1, username);
        ps.setString(2, userpass);
        ps.setString(3, "customer");
        rs = ps.executeUpdate();
        if(rs==1)
        {
            flag=true;
        }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return flag;
        }
}

 

步驟五:程式_ Servlet

擷取部分:登入


package com.sxdx.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.Cookie;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sxdx.dao.UserInfoDAO;
public class LoginServlet extends HttpServlet {
       /**
        * Constructor of the object.
        */
       public LoginServlet() {
              super();
       }
       /**
        * Destruction of the servlet. <br>
        */
       public void destroy() {
              super.destroy(); // Just puts "destroy" string in log
              // Put your code here
       }
       /**
        * 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 {
              response.setContentType("text/html;charset=utf-8");
              request.setCharacterEncoding("utf-8");
              String username=request.getParameter("username");
              String userpass=request.getParameter("userpass");
              UserInfoDAO userDAO=new UserInfoDAO();
              int result=userDAO.checkLogin(username, userpass);
              if(result!=0)
              {
                      Cookie cookie_username = new Cookie("username", java.net.URLEncoder.encode(username, "utf-8"));
                   cookie_username.setMaxAge(60*60);
                   cookie_username.setPath("/");
                   response.addCookie(cookie_username);
              if(result==1)
              {
                     request.getRequestDispatcher("/foodinfoservlet").forward(request,response);
              }
              if(result==2)
              {
                     response.sendRedirect("guanli.jsp");
              }
              }
              else
              {
                      PrintWriter out = response.getWriter();
                      out.print("<script>"   "alert('您輸入的賬號密碼有誤');"  "document.location.href='index.jsp';" "</script>");
                      out.close();
              }
       }
       /**
        * 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);
       }
       /**
        * Initialization of the servlet. <br>
        *
        * @throws ServletException if an error occurs
        */
       public void init() throws ServletException {
              // Put your code here
       }
}

步驟六:Web層_JSP

擷取部分:index

<%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
   
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">   
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
 
  <body style="width:760px; height:700px; text-align: center;">
   <div style="width:760px; align="center">
       <div style="height:141px;">
       <%@ include file="top.jsp" %>
       </div>
       <div id="centent" style="width:760px;height:100%; position:relative;">
           <div style=" width:160px; height:240px; position:absolute; left:0px;top:0px; float:left;">
           <%@ include file="left.jsp" %>
           </div>
           <div style="width:600px;height:111px;float:right;">
           <%@ include file="right_top.jsp" %>
           </div>
           <div style="width:600px; height:240px;float:right;">
           <div style="height:20px; background-color:#AAB9BD">
           新系統使用者請先完成註冊
           </div>
           <form action="/buyEat/loginservlet?op=login" method="post" style="height: 100px; width:300px; ">
                <br/>使用者名稱:<input type="text" name="username" style="border:1px solid #666666; size: 17px;"  /><br/><br/>
                密&nbsp;&nbsp;碼:&nbsp;&nbsp;&nbsp;<input type="password" name="userpass"  style="border:1px solid #666666;size: 17px;" /><br/><br/>
                <input type="submit" value="登入">
           </form>
           <input type="button" value="註冊" onClick="window.location.href='zhuce.jsp'">  
           </div></div>
           </div>
       <div>
       <%@ include file="bottom.jsp" %>
       </div>
  </body>
</html>

 

 

 

實驗結果

以使用者名稱wubifen,密碼970000完成以下結果測試

效果一: 實現商家和使用者兩種角色的註冊與登入

  1. 使用者註冊與登入

主頁:

新使用者註冊:

查詢資料庫中對應的表:

 

登入:成功後可以瀏覽店鋪資訊

 

 

  1. 商家登入

 

 

效果二: 使用者名稱存入cookie並顯示在頁面上

使用者名稱存入cookie後顯示在頁面上的效果

 

效果三: 選某一件菜品,選好之後提交

對應圖片點選進去後:

再次點選訂購完成提交

 

效果四: 使用socket通訊

完成訂單的提交後

 

使用商家使用者登入檢視訂單

商家點選確認訂單

對應看顧客的訂單狀態:處於confirm被接受狀態

 

 

附加效果五: 一次提交多件菜品

附加效果六:檢視訂單歷史

原始碼:

連結:https://pan.baidu.com/s/1QwoEJEB8PPGsXY76ifAYnw 密碼:7lsi

總結:

這次實驗的課程設計java web專案,使用JSP Servlet JavaBean實現MVC模式,使用cookie並把資訊顯示在頁面上,使用socket實現網路通訊,進行註冊、登入、瀏覽菜品、下訂單、檢視訂單、檢視歷史訂單、多角色使用者登入登操作,遇到了很多困難,抓取了網上資料庫資料以及顯示時鐘時間等功能去美化頁面。

第一次嘗試完成使用Java語言實現的系統,除了鞏固課堂知識,是更多的意識到自身對Java學習的不夠。Java是很有用的語言,JSP讓我接觸到了全新的程式設計,也讓我知道,學無止境。