Java MVC Architecture
The Model-View-Controller (MVC) architecture organizes the application into three layers:
- Model: Represents the application’s data and business logic. This layer interacts with the database.
- View: Handles the user interface, often using JSP or HTML.
- Controller: Manages user requests, processes them, and determines the appropriate response. Servlets typically act as controllers in Java web applications5.
Understanding Java MVC Architecture with Simple Examples
The Model-View-Controller (MVC) architecture can be compared to how a restaurant operates with three main groups:
- Chefs (Model)
- are responsible for preparing the food (data and logic).
- Waiters (Controller)
- take your orders and relay them to the chefs.
- Menu (View)
- displays the choices and the final meals.
Let’s see how these components function in a Java web application, using a hotel booking system as an example: 1. Model (Data and Rules) The Model acts like a database supervisor. It keeps track of and organizes data, such as hotel rooms or reservations.
Let us consider a practical system (Hotel Booking System)
NOTE: we will learn how to configure the below files in future lessons for now just observe the code structure to get a rough idea
1. Model (Data and Rules)
- The Model acts like a database supervisor.
- It keeps track of and organizes data, such as hotel rooms or reservations.
- This class keeps the details of the rooms and manages the booking process.
public class HotelRoom {
private int roomNumber;
private boolean isBooked;
// Getters and setters
public boolean isBooked() { return isBooked; }
public void bookRoom() { isBooked = true; }
}
}
2. View (User Interface)
- The View is what users see on the webpage.
- It shows information like available rooms and takes in user input, such as booking requests.
- Example (JSP):
<!-- Show available rooms -->
<h1>Available Rooms</h1>
<% for (HotelRoom room : rooms) { %>
<p>Room <%= room.getRoomNumber() %>:
<%= room.isBooked() ? "Booked" : "Available" %></p>
<% } %>
3. Controller (Request Handler)
- The Controller is like a traffic officer.
- It handles what users do, like when they click “Book Now,” and makes changes to the Model and View.
- Example (Servlet):
public class BookingServlet extends HttpServlet {
protected void doPost(HttpRequest request, HttpResponse response) {
int roomNumber = Integer.parseInt(request.getParameter("room"));
HotelRoom room = database.getRoom(roomNumber);
room.bookRoom(); // Update Model
response.sendRedirect("/confirmation.jsp"); // Show confirmation View
}
}
How They Work Together: A Hotel Booking Scenario
- User Action: You click “Book Room 101” on the website (View).
- Controller: The
BookingServlet
receives your request. - Model: The servlet updates the
HotelRoom
object in the database (marks it as booked). - View: The user sees a confirmation page (
confirmation.jsp
).