0% found this document useful (0 votes)
14 views26 pages

Workshop 1

The Food Order Management System is a Java web application that facilitates online food ordering, featuring user registration, login, and food item management by admins. It employs MVC2 architecture, utilizes SQL Server for database management, and includes session management for user interactions. The system allows users to browse food items, manage a shopping cart, and place orders while providing admins with tools to manage food inventory and view orders.

Uploaded by

Thành Đạt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views26 pages

Workshop 1

The Food Order Management System is a Java web application that facilitates online food ordering, featuring user registration, login, and food item management by admins. It employs MVC2 architecture, utilizes SQL Server for database management, and includes session management for user interactions. The system allows users to browse food items, manage a shopping cart, and place orders while providing admins with tools to manage food inventory and view orders.

Uploaded by

Thành Đạt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Workshop 1: Food Order Management System

Objective
The Food Order Management System is a Java web application designed to
manage the process of ordering food online. The system provides user registration
and login functionality, allows users to browse and order food, and enables admins
to manage food items and view orders. The application uses the MVC2
architecture with a centralized MainController servlet for request handling and
includes session management to maintain user states.

Requirements
Functional Requirements
1. User Registration and Login, Welcome, Logout:
o Users can register and log in to place orders.

o Sessions are maintained for logged-in users, with session expiration for
inactivity.
2. Food Item Management (Admin):
o Admins can create, view, update, and delete food items.

3. Order Placement (User):


o Users can browse food items, add them to a cart, and place orders.

4. Order Management (Admin):


o Admins can view a list of all orders and their details.

5. Shopping Cart Management:


o Users can dynamically add, update, and remove items from the cart.

Non-Functional Requirements
1. Use SQL Server for database management.
2. Implement MVC2 architecture.
3. Maintain session security with attributes such as HttpOnly and Secure.
4. Use Bootstrap for responsive and user-friendly UI (optional).
Folder Structure (MVC2 Architecture)
FoodOrderManagement/

├── src/
│ ├── com.example.controller/ # Controllers
│ │ ├── MainController.java
│ │ ├── LoginController.java
│ │ ├── RegisterController.java
│ │ ├── FoodController.java
│ │ ├── CartController.java
│ │ └── OrderController.java
│ │
│ ├── com.example.dao/ # Data Access Objects
│ │ ├── UserDAO.java
│ │ ├── FoodDAO.java
│ │ ├── CartDAO.java
│ │ └── OrderDAO.java
│ │
│ ├── com.example.dto/ # Data Transfer Objects
│ │ ├── User.java
│ │ ├── FoodItem.java
│ │ ├── CartItem.java
│ │ └── Order.java
│ │
│ └── com.example.util/ # Utility Classes
│ └── DatabaseConnection.java

├── WebContent/
│ ├── css/ # Stylesheets
│ │ └── styles.css
│ │
│ ├── js/ # JavaScript Files
│ │ └── scripts.js
│ │
│ ├── views/ # JSP Pages
│ │ ├── login.jsp
│ │ ├── register.jsp
│ │ ├── foodList.jsp
│ │ ├── cart.jsp
│ │ ├── checkout.jsp
│ │ ├── admin/ # Admin JSPs
│ │ │ ├── manageFood.jsp
│ │ │ └── viewOrders.jsp
│ │
│ └── WEB-INF/
│ ├── web.xml # Deployment Descriptor
│ └── lib/ # JAR Dependencies

Database Schema
Database Name: FoodOrderDB
1. tblUsers
o Stores user information, including credentials and roles.

Field Name Type Validation

userID VARCHAR(50) Primary Key, Not null

NVARCHAR(50
fullName Not null
0)

VARCHAR(100
email Not null, Unique
)

phoneNumb VARCHAR(15) Not null, Format: [0-9]


Field Name Type Validation

er {10,15}

roleID NVARCHAR(5) Not null

password VARCHAR(50) Not null

2. tblFoodItems
o Stores food item details.

Field
Type Validation
Name

Primary Key, Not


foodID VARCHAR(50)
null

NVARCHAR(20
foodName Not null
0)

DECIMAL(18,2
price Not null
)

quantity INT Not null

NVARCHAR(10
category Not null
0)

3. tblOrders
o Stores orders placed by users.

Field
Type Validation
Name

VARCHAR(50
orderID Primary Key, Not null
)

VARCHAR(50 Foreign Key


userID
) (tblUsers.userID)

orderDate DATE Not null

totalAmou DECIMAL(18,
Not null
nt 2)

4. tblOrderDetails
o Stores details of each order.
Field
Type Validation
Name

orderDetailI Primary Key, Identity (Auto


INT
D Increment)

VARCHAR(50
orderID Foreign Key (tblOrders.orderID)
)

VARCHAR(50 Foreign Key


foodID
) (tblFoodItems.foodID)

quantity INT Not null

DECIMAL(18,
price Not null
2)

Grading Criteria

Mark
Feature Description
s

User Registration and Login, Welcome, User management with session


2.5
Logout, Session handling.

Admin CRUD operations for food


Food Management 2.5
items.

Dynamic cart updates with session-


Shopping Cart Management 2.5
based storage.

Checkout and order storage in the


Order Placement 2.5
database.

Total 10.0

Step 0: Create Database


SQL script to create the database and necessary tables.
-- Create the database
CREATE DATABASE FoodOrderDB;

USE FoodOrderDB;
-- Create tblUsers
CREATE TABLE tblUsers (
userID VARCHAR(50) PRIMARY KEY NOT NULL,
fullName NVARCHAR(500) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
phoneNumber VARCHAR(15) NOT NULL,
roleID NVARCHAR(5) NOT NULL,
password VARCHAR(50) NOT NULL
);

INSERT INTO tblUsers (userID, fullName, email, phoneNumber, roleID, password)


VALUES
('user1', 'Alice Brown', '[email protected]', '1234567890', 'USR', 'password1'),
('admin', 'Admin User', '[email protected]', '9876543210', 'ADM',
'adminpassword');

-- Create tblFoodItems
CREATE TABLE tblFoodItems (
foodID VARCHAR(50) PRIMARY KEY NOT NULL,
foodName NVARCHAR(200) NOT NULL,
price DECIMAL(18,2) NOT NULL,
quantity INT NOT NULL,
category NVARCHAR(100) NOT NULL
);

INSERT INTO tblFoodItems (foodID, foodName, price, quantity, category) VALUES


('F001', 'Margherita Pizza', 10.99, 50, 'Pizza'),
('F002', 'Caesar Salad', 7.99, 30, 'Salad'),
('F003', 'Cheeseburger', 8.99, 40, 'Burger');
-- Create tblOrders
CREATE TABLE tblOrders (
orderID VARCHAR(50) PRIMARY KEY NOT NULL,
userID VARCHAR(50),
orderDate DATE NOT NULL,
totalAmount DECIMAL(18,2) NOT NULL,
FOREIGN KEY (userID) REFERENCES tblUsers(userID)
);

-- Create tblOrderDetails
CREATE TABLE tblOrderDetails (
orderDetailID INT IDENTITY(1,1) PRIMARY KEY,
orderID VARCHAR(50),
foodID VARCHAR(50),
quantity INT NOT NULL,
price DECIMAL(18,2) NOT NULL,
FOREIGN KEY (orderID) REFERENCES tblOrders(orderID),
FOREIGN KEY (foodID) REFERENCES tblFoodItems(foodID)
);

Implementation Guide
Step 1: Database Connection Utility
File: DatabaseConnection.java
package com.example.util;

import java.sql.Connection;
import java.sql.DriverManager;

public class DatabaseConnection {


public static Connection initializeDatabase() throws Exception {
String jdbcURL =
"jdbc:sqlserver://localhost:1433;databaseName=FoodOrderDB";
String jdbcUsername = "sa";
String jdbcPassword = "your_password";

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
return DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword);
}
}

Step 2: Main Controller


File: MainController.java
package com.example.controller;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

public class MainController extends HttpServlet {


protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String action = request.getParameter("action");
String url = "login.jsp"; // Default redirection

try {
switch (action) {
case "Login":
url = "LoginController";
break;
case "Register":
url = "RegisterController";
break;
case "ViewFoods":
url = "FoodController";
break;
case "AddToCart":
url = "CartController";
break;
case "PlaceOrder":
url = "OrderController";
break;
default:
request.setAttribute("ERROR", "Action not supported.");
}
} catch (Exception e) {
log("Error at MainController: " + e.toString());
} finally {
request.getRequestDispatcher(url).forward(request, response);
}
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}
}

Step 3: Login Controller


File: LoginController.java
package com.example.controller;

import com.example.dao.UserDAO;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

public class LoginController extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String userID = request.getParameter("userID");
String password = request.getParameter("password");

try {
boolean isAuthenticated = new UserDAO().authenticateUser(userID,
password);

if (isAuthenticated) {
HttpSession session = request.getSession();
session.setAttribute("userID", userID);
response.sendRedirect("MainController?action=ViewFoods");
} else {
request.setAttribute("ERROR", "Invalid credentials.");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
}
1. register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>User Registration</title>
</head>
<body>
<h2>Register</h2>
<form action="MainController" method="post">
<input type="hidden" name="action" value="Register">
<label for="fullName">Full Name:</label>
<input type="text" name="fullName" required><br><br>

<label for="email">Email:</label>
<input type="email" name="email" required><br><br>

<label for="phoneNumber">Phone Number:</label>


<input type="text" name="phoneNumber" required><br><br>
<label for="password">Password:</label>
<input type="password" name="password" required><br><br>

<input type="submit" value="Register">


</form>
<%
String error = (String) request.getAttribute("ERROR");
if (error != null) {
%>
<p style="color:red;"><%= error %></p>
<%
}
%>
</body>
</html>

2. cart.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.List" %>
<%@ page import="com.example.dto.CartItem" %>
<html>
<head>
<title>Your Cart</title>
</head>
<body>
<h2>Your Shopping Cart</h2>
<table border="1">
<tr>
<th>Food Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
<th>Actions</th>
</tr>
<%
List<CartItem> cartItems = (List<CartItem>)
request.getAttribute("cartItems");
if (cartItems != null && !cartItems.isEmpty()) {
for (CartItem item : cartItems) {
%>
<tr>
<td><%= item.getFoodName() %></td>
<td><%= item.getQuantity() %></td>
<td><%= item.getPrice() %></td>
<td><%= item.getTotal() %></td>
<td>
<form action="MainController" method="post" style="display:inline;">
<input type="hidden" name="action" value="UpdateCart">
<input type="hidden" name="foodID" value="<%= item.getFoodID()
%>">
<input type="number" name="quantity" value="<%=
item.getQuantity() %>" min="1">
<input type="submit" value="Update">
</form>
<form action="MainController" method="post" style="display:inline;">
<input type="hidden" name="action" value="RemoveFromCart">
<input type="hidden" name="foodID" value="<%= item.getFoodID()
%>">
<input type="submit" value="Remove">
</form>
</td>
</tr>
<%
}
} else {
%>
<tr>
<td colspan="5">Your cart is empty.</td>
</tr>
<%
}
%>
</table>
<br>
<a href="MainController?action=ViewFoods">Continue Shopping</a>
<form action="MainController" method="post">
<input type="hidden" name="action" value="Checkout">
<input type="submit" value="Checkout">
</form>
</body>
</html>

3. checkout.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.List" %>
<%@ page import="com.example.dto.CartItem" %>
<html>
<head>
<title>Checkout</title>
</head>
<body>
<h2>Checkout</h2>
<table border="1">
<tr>
<th>Food Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
<%
List<CartItem> cartItems = (List<CartItem>)
request.getAttribute("cartItems");
double totalAmount = 0.0;
if (cartItems != null && !cartItems.isEmpty()) {
for (CartItem item : cartItems) {
totalAmount += item.getTotal();
%>
<tr>
<td><%= item.getFoodName() %></td>
<td><%= item.getQuantity() %></td>
<td><%= item.getPrice() %></td>
<td><%= item.getTotal() %></td>
</tr>
<%
}
}
%>
</table>
<h3>Total Amount: $<%= totalAmount %></h3>
<form action="MainController" method="post">
<input type="hidden" name="action" value="PlaceOrder">
<input type="hidden" name="totalAmount" value="<%= totalAmount %>">
<input type="submit" value="Confirm Order">
</form>
</body>
</html>

4. manageFood.jsp (Admin)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.List" %>
<%@ page import="com.example.dto.FoodItem" %>
<html>
<head>
<title>Manage Food</title>
</head>
<body>
<h2>Manage Food Items</h2>
<a href="createFood.jsp">Add New Food Item</a>
<table border="1">
<tr>
<th>Food Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Category</th>
<th>Actions</th>
</tr>
<%
List<FoodItem> foodItems = (List<FoodItem>)
request.getAttribute("foodItems");
if (foodItems != null) {
for (FoodItem item : foodItems) {
%>
<tr>
<td><%= item.getFoodName() %></td>
<td><%= item.getPrice() %></td>
<td><%= item.getQuantity() %></td>
<td><%= item.getCategory() %></td>
<td>
<form action="MainController" method="post" style="display:inline;">
<input type="hidden" name="action" value="EditFood">
<input type="hidden" name="foodID" value="<%= item.getFoodID()
%>">
<input type="submit" value="Edit">
</form>
<form action="MainController" method="post" style="display:inline;">
<input type="hidden" name="action" value="DeleteFood">
<input type="hidden" name="foodID" value="<%= item.getFoodID()
%>">
<input type="submit" value="Delete">
</form>
</td>
</tr>
<%
}
}
%>
</table>
</body>
</html>
===============================
1. FoodController.java
package com.example.controller;

import com.example.dao.FoodDAO;
import com.example.dto.FoodItem;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/FoodController")
public class FoodController extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
String action = request.getParameter("action");
FoodDAO foodDAO = new FoodDAO();

try {
if ("ViewFoods".equals(action)) {
List<FoodItem> foodItems = foodDAO.getAllFoodItems();
request.setAttribute("foodItems", foodItems);
request.getRequestDispatcher("views/foodList.jsp").forward(request,
response);
} else if ("EditFood".equals(action)) {
String foodID = request.getParameter("foodID");
FoodItem food = foodDAO.getFoodById(foodID);
request.setAttribute("food", food);

request.getRequestDispatcher("views/admin/editFood.jsp").forward(request,
response);
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("ERROR", "Error processing food request.");
request.getRequestDispatcher("views/error.jsp").forward(request, response);
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
String action = request.getParameter("action");
FoodDAO foodDAO = new FoodDAO();

try {
if ("CreateFood".equals(action)) {
String foodName = request.getParameter("foodName");
double price = Double.parseDouble(request.getParameter("price"));
int quantity = Integer.parseInt(request.getParameter("quantity"));
String category = request.getParameter("category");

FoodItem food = new FoodItem(null, foodName, price, quantity,


category);
foodDAO.addFood(food);
response.sendRedirect("MainController?action=ViewFoods");
} else if ("UpdateFood".equals(action)) {
String foodID = request.getParameter("foodID");
String foodName = request.getParameter("foodName");
double price = Double.parseDouble(request.getParameter("price"));
int quantity = Integer.parseInt(request.getParameter("quantity"));
String category = request.getParameter("category");

FoodItem food = new FoodItem(foodID, foodName, price, quantity,


category);
foodDAO.updateFood(food);
response.sendRedirect("MainController?action=ViewFoods");
} else if ("DeleteFood".equals(action)) {
String foodID = request.getParameter("foodID");
foodDAO.deleteFood(foodID);
response.sendRedirect("MainController?action=ViewFoods");
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("ERROR", "Error processing food request.");
request.getRequestDispatcher("views/error.jsp").forward(request, response);
}
}
}

2. CartController.java
package com.example.controller;

import com.example.dao.CartDAO;
import com.example.dto.CartItem;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/CartController")
public class CartController extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
HttpSession session = request.getSession();
CartDAO cartDAO = new CartDAO();

try {
List<CartItem> cartItems = cartDAO.getCartItems(session);
request.setAttribute("cartItems", cartItems);
request.getRequestDispatcher("views/cart.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("ERROR", "Failed to retrieve cart items.");
request.getRequestDispatcher("views/error.jsp").forward(request, response);
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
String action = request.getParameter("action");
HttpSession session = request.getSession();
CartDAO cartDAO = new CartDAO();
try {
if ("AddToCart".equals(action)) {
String foodID = request.getParameter("foodID");
int quantity = Integer.parseInt(request.getParameter("quantity"));
cartDAO.addToCart(session, foodID, quantity);
response.sendRedirect("MainController?action=ViewCart");
} else if ("UpdateCart".equals(action)) {
String foodID = request.getParameter("foodID");
int quantity = Integer.parseInt(request.getParameter("quantity"));
cartDAO.updateCart(session, foodID, quantity);
response.sendRedirect("MainController?action=ViewCart");
} else if ("RemoveFromCart".equals(action)) {
String foodID = request.getParameter("foodID");
cartDAO.removeFromCart(session, foodID);
response.sendRedirect("MainController?action=ViewCart");
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("ERROR", "Failed to process cart action.");
request.getRequestDispatcher("views/error.jsp").forward(request, response);
}
}
}

3. OrderController.java
package com.example.controller;

import com.example.dao.CartDAO;
import com.example.dao.OrderDAO;
import com.example.dto.CartItem;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/OrderController")
public class OrderController extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
String action = request.getParameter("action");
HttpSession session = request.getSession();
OrderDAO orderDAO = new OrderDAO();
CartDAO cartDAO = new CartDAO();

try {
if ("Checkout".equals(action)) {
List<CartItem> cartItems = cartDAO.getCartItems(session);
request.setAttribute("cartItems", cartItems);
request.getRequestDispatcher("views/checkout.jsp").forward(request,
response);
} else if ("PlaceOrder".equals(action)) {
String userID = (String) session.getAttribute("userID");
double totalAmount =
Double.parseDouble(request.getParameter("totalAmount"));
orderDAO.placeOrder(userID, totalAmount, session);
session.removeAttribute("cartItems"); // Clear the cart after placing order
response.sendRedirect("views/orderConfirmation.jsp");
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("ERROR", "Failed to process order.");
request.getRequestDispatcher("views/error.jsp").forward(request, response);
}
}
}

4. createFood.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Create Food</title>
</head>
<body>
<h2>Create a New Food Item</h2>
<form action="MainController" method="post">
<input type="hidden" name="action" value="CreateFood">

<label for="foodName">Food Name:</label>


<input type="text" name="foodName" required><br><br>

<label for="price">Price:</label>
<input type="number" step="0.01" name="price" required><br><br>

<label for="quantity">Quantity:</label>
<input type="number" name="quantity" required><br><br>
<label for="category">Category:</label>
<input type="text" name="category" required><br><br>

<input type="submit" value="Create Food">


</form>
</body>
</html>

5. editFood.jsp
jsp
Copy code
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.example.dto.FoodItem" %>
<html>
<head>
<title>Edit Food</title>
</head>
<body>
<%
FoodItem food = (FoodItem) request.getAttribute("food");
%>
<h2>Edit Food: <%= food.getFoodName() %></h2>
<form action="MainController" method="post">
<input type="hidden" name="action" value="UpdateFood">
<input type="hidden" name="foodID" value="<%= food.getFoodID() %>">

<label for="foodName">Food Name:</label>


<input type="text" name="foodName" value="<%= food.getFoodName() %>"
required><br><br>
<label for="price">Price:</label>
<input type="number" step="0.01" name="price" value="<%=
food.getPrice() %>" required><br><br>

<label for="quantity">Quantity:</label>
<input type="number" name="quantity" value="<%= food.getQuantity() %>"
required><br><br>

<label for="category">Category:</label>
<input type="text" name="category" value="<%= food.getCategory() %>"
required><br><br>

<input type="submit" value="Update Food">


</form>
</body>
</html>

You might also like