Java CRUD Application Introduction

Java MVC Architecture

The Model-View-Controller (MVC) architecture organizes the application into three layers:

  1. Model: Represents the application’s data and business logic. This layer interacts with the database.
  2. View: Handles the user interface, often using JSP or HTML.
  3. Controller: Manages user requests, processes them, and determines the appropriate response. Servlets typically act as controllers in Java web applications5.

The Model-View-Controller (MVC) architecture can be compared to how a restaurant operates with three main groups:

  1. Chefs (Model)
    • are responsible for preparing the food (data and logic).
  2. Waiters (Controller)
    • take your orders and relay them to the chefs.
  3. 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.

  • 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; }
}

}
    
  • 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>
<% } %>
  • 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
    }
}

    
  1. User Action: You click “Book Room 101” on the website (View).
  2. Controller: The BookingServlet receives your request.
  3. Model: The servlet updates the HotelRoom object in the database (marks it as booked).
  4. View: The user sees a confirmation page (confirmation.jsp).

Pages: 1 2