Version: 1.0.0
Last Updated: December 3, 2025
Status: Published
Audience: Architects, Tech Leads, Senior Developers
Prerequisite: Project Overview
IoT Bay follows a 3-tier Model-View-Controller (MVC) architecture with clear separation of concerns:
βββββββββββββββββββββββββββββββββββββββββββ
β Presentation Layer β
β JSP Pages + HTML/CSS/JavaScript β
β (Atomic Design) β
ββββββββββββββββββ¬βββββββββββββββββββββββββ
β
βββββββββββββββββββ΄βββββββββββββββββββββββββ
β Controller Layer (Servlets) β
β @WebServlet annotations β
β HTTP request/response handling β
ββββββββββββββββββ¬βββββββββββββββββββββββββ
β
βββββββββββββββββββ΄βββββββββββββββββββββββββ
β Service Layer (Business Logic) β
β UserService, ProductService, etc. β
β Validation + business rules β
ββββββββββββββββββ¬βββββββββββββββββββββββββ
β
βββββββββββββββββββ΄βββββββββββββββββββββββββ
β Data Access Layer (DAO Pattern) β
β Interface-based design (interfaces/) β
β JDBC + PreparedStatements β
ββββββββββββββββββ¬βββββββββββββββββββββββββ
β
βββββββββββββββββββ΄βββββββββββββββββββββββββ
β Database Layer (SQLite/PostgreSQL) β
β Relational schema with normalization β
βββββββββββββββββββββββββββββββββββββββββββ
Files: src/main/webapp/*.jsp, src/main/webapp/components/, src/main/webapp/css/
Responsibilities:
- Render HTML for user interaction
- Component-based using Atomic Design (Atoms β Molecules β Organisms)
- Responsive CSS with modern design system
- Form handling + client-side validation
Key Concepts:
- JSP: Server-side templating
- Components: Reusable modules (
product-card.jsp,modal.jsp, etc.) - Design System: Centralized CSS (
modern-theme.css)
Files: src/main/java/controller/*Controller.java
Responsibilities:
- HTTP request entry points (
@WebServletannotations) - Route requests to appropriate methods (
doGet,doPost) - Initialize DAOs/Services in
init()method - Handle errors (IllegalArgumentException, SQLException)
Pattern:
@WebServlet("/resource/*")
public class ResourceController extends HttpServlet {
private ResourceDAO resourceDAO;
private ResourceService resourceService;
@Override
public void init() throws ServletException {
// 1. Get connection
Connection connection = DIContainer.getConnection();
// 2. Initialize DAOs
resourceDAO = new ResourceDAO(connection);
// 3. Throw ServletException if fails
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
// 1. Get data from request
// 2. Call service/DAO
// 3. Forward to JSP
}
}Key Files: Backend Developer Guide
Files: src/main/java/service/*Service.java
Responsibilities:
- Validation (email format, password strength, etc.)
- Business rules (e.g., "email must be unique")
- Orchestration (call multiple DAOs for complex operations)
- Error handling (throw
IllegalArgumentExceptionfor validation,SQLExceptionfor DB)
Pattern:
public class UserService {
private final UserDAO userDAO;
public User registerUser(UserRegistrationRequest request) throws SQLException {
// 1. Validate
if (!isValidEmail(request.getEmail())) {
throw new IllegalArgumentException("Invalid email");
}
// 2. Check business rules
if (userDAO.getUserByEmail(request.getEmail()) != null) {
throw new IllegalArgumentException("Email already exists");
}
// 3. Create and return
User user = new User(request);
userDAO.createUser(user);
return user;
}
}Key Files: Backend Developer Guide
Files:
src/main/java/dao/interfaces/*DAO.java(contracts)src/main/java/dao/*DAOImpl.java(implementations)
Responsibilities:
- Database operations (CRUD)
- SQL execution via JDBC
- Result set mapping to objects
- Resource cleanup (try-with-resources)
Pattern:
// Interface (contract)
public interface UserDAO {
void createUser(User user) throws SQLException;
User getUserById(int id) throws SQLException;
User getUserByEmail(String email) throws SQLException;
}
// Implementation (JDBC)
public class UserDAOImpl implements UserDAO {
private final Connection connection;
@Override
public void createUser(User user) throws SQLException {
String sql = "INSERT INTO users (email, name, password) VALUES (?, ?, ?)";
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
stmt.setString(1, user.getEmail());
stmt.setString(2, user.getName());
stmt.setString(3, user.getPassword());
stmt.executeUpdate();
}
}
}Best Practices:
- Always use
PreparedStatement(prevent SQL injection) - Use try-with-resources for resource cleanup
- Throw
SQLException, don't catch - All methods throw
SQLException
Files: src/main/resources/iotbay.db (SQLite, dev) or PostgreSQL (prod)
Schema: Normalized relational design with 12+ tables
Key Entities:
- Users, Addresses, Reset Questions
- Categories, Products, Reviews
- Carts, Orders, Payments
- Access Logs, Wishlist Items
Pattern 1: Direct Factory (Legacy, used in HomeController)
Connection connection = DBConnection.getConnection(); // Static factory
productDAO = new ProductDAOImpl(connection);Pattern 2: Dependency Injection (Recommended for new code)
Connection connection = DIContainer.getConnection(); // DI container
cartItemDAO = new CartItemDAO(connection);DBConnection.getConnection()β UsesAppConfig(db.url, db.driver)DIContainer.getConnection()β Managed connection lifecycle- Prefer DIContainer for testability and potential connection pooling
1. User Request (Browser)
β
2. Servlet Router (@WebServlet path)
β
3. Controller.init() β Initialize DAOs (once per servlet lifecycle)
β
4. Controller.doGet/doPost() β Handle request
βββ Extract parameters (request.getParameter)
βββ Call Service (validation + business logic)
βββ Call DAO (database operation)
βββ Handle errors (catch IllegalArgumentException or SQLException)
βββ Prepare response (request.setAttribute, response.sendRedirect)
βββ Forward to JSP (request.getRequestDispatcher)
β
5. JSP Rendering (server-side template)
β
6. HTML Response (Browser)
Controller (Entry point)
ββ Catch IllegalArgumentException
β βββ Validation error β Show form with error message
β
ββ Catch SQLException
β βββ Database error β Log error, show generic message
β
ββ Throw ServletException (if DAO initialization fails in init())
βββ Container error β 500 Internal Server Error
Read: Backend Developer Guide - Error Handling
- Session-based authentication (
HttpSession) - Password hashing (SHA-256 with salt)
- Role-based access control (admin vs. user)
- Server-side validation (critical)
ValidationUtilclass for email, passwords, etc.PasswordUtilfor hashing
PreparedStatement(parameterized queries)- Never concatenate SQL strings
- Token-based CSRF checks
- Same-origin validation
- RESTful conventions (GET, POST, PUT, DELETE)
- URL versioning (
/api/v1/...) - JSON responses (via GSON)
- Service layer provides business logic
- Controllers translate requests to service calls
- Response formatting via GSON
GET /products?categoryId=1
β ProductController.doGet()
ββ Extract categoryId
ββ ProductService.getProductsByCategory(categoryId)
ββ ProductDAO.getProductsByCategory(1)
ββ Return list of Products
ββ Format as JSON (GSON)
ββ Response 200 OK
Read: API Design & API Reference
User (1) ββββ (M) Address
User (1) ββββ (M) Order
User (1) ββββ (M) Review
User (1) ββββ (M) Wishlist
Category (1) ββββ (M) Product
Product (1) ββββ (M) Review
Product (1) ββββ (M) CartItem
Product (1) ββββ (M) OrderProduct
Order (1) ββββ (1) Payment
Order (1) ββββ (M) OrderProduct
OrderProduct (M) ββββ (1) Product
CartItem (M) ββββ (1) Product
-- Get user's orders with product details
SELECT o.*, op.*, p.*
FROM orders o
JOIN order_products op ON o.id = op.order_id
JOIN products p ON op.product_id = p.id
WHERE o.user_id = ?
-- Get products in category with average rating
SELECT p.*, AVG(r.rating) as avg_rating
FROM products p
LEFT JOIN reviews r ON p.id = r.product_id
WHERE p.category_id = ?
GROUP BY p.id- Atoms: Basic elements (buttons, inputs, labels)
- Molecules: Simple components (search bar, card)
- Organisms: Complex components (header, product grid)
src/main/webapp/components/
βββ atoms/ # Reusable basic elements
βββ molecules/ # Simple combined components
βββ organisms/ # Complex components
βββ templates/ # Page layouts
- Centralized CSS (
modern-theme.css) - Color palette, typography, spacing
- Responsive grid system
- WCAG 2.1 AA accessibility compliance
Read: Component Architecture & Design System
- SQLite single-file database (dev only)
- No caching layer (direct DB queries)
- Single-threaded servlet handling
- Switch to PostgreSQL for multi-user concurrency
- Implement connection pooling (HikariCP)
- Add caching layer (Redis)
- Async processing for heavy operations
- Real-time notifications (WebSockets)
- Recommendation engine (Machine Learning)
- Internationalization (i18n)
- Unit Tests: Service layer business logic
- Integration Tests: DAO + Database
- E2E Tests: Full request-response flow
/ \
/E2E\ Few end-to-end tests
/-----\
/ Tests \
/---------\
/ Integration\ Some integration tests
/------------- \
/ Unit Tests \ Many unit tests
/_________________ \
- Component Architecture - Frontend structure
- Database Design - Schema details
- API Design - API patterns
- Security Architecture - Security details
- Backend Developer Guide - Coding patterns
- Frontend Developer Guide - JSP/CSS patterns
- Code Style Guide - Conventions
- Test Strategy - Testing approach
- Error Prevention - Prevent common errors
| Decision | Rationale | Trade-off |
|---|---|---|
| MVC 3-tier | Clear separation of concerns | Extra boilerplate vs. monolith |
| DAO Pattern | Interface-based, testable | Abstraction layer overhead |
| Servlet-based | University requirement, proven | Not async/reactive |
| SQLite (dev) | Zero setup, file-based | Single-user, not production-ready |
| PreparedStatement | SQL injection prevention | Slight performance cost |
| Atomic Design | Reusable, maintainable components | Learning curve |
- Separation of Concerns: Each layer has one job
- DRY (Don't Repeat Yourself): Reuse components and utilities
- SOLID Principles: Single responsibility, open/closed, Liskov substitution
- Fail Fast: Validate early, throw exceptions
- Security First: Prevent injection, validate input, handle errors
- Accessibility First: WCAG 2.1 AA compliance from the start
Have questions? Need to discuss architectural changes?
- Check Architecture Index above
- Read Component Architecture for details
- Review Database Design for schema
- Consult Backend Guide for implementation patterns
- Reach out to tech lead for design discussions
Version: 1.0.0
Status: Published
Maintained By: IoT Bay Architecture Team
Last Updated: December 3, 2025
Document Version: 1.0.0