πŸ•ΉοΈ MVC Pattern

GunhoΒ·2024λ…„ 10μ›” 29일
1

Object Oriented Programming (OOP) & Java

λͺ©λ‘ 보기
11/29

πŸ•ΉοΈ MVC Pattern

πŸ•ΉοΈ MVC (Model-View-Controller) pattern refers to a software engineering practice where it divides an application into three components: Model, View, and Controller.

Each component of the MVC pattern is responsible for:

  • model: the database and business-related logics.

  • view: an interface that displays information (response) to the user

  • controller: user input management and workflow coordination between the model and the view.

The MVC pattern, if applied appropriately:

  • improves component reusability and maintainability.
  • simplifies the overall development process.
  • increases testability of the application.

The MVC pattern has evolved over time, resulting in several different iterations and implementations. They are namely:

  • ❄️ MVC1
  • ☁️ MVC2
  • 🌿 Spring MVC

and will be discussed in the following sections.

❄️ MVC1

❄️ MVC1 is a very primitive form of theMVC practices where a model, view and a controller are implemented in a single JSP file.

JSP often employed service classes or Java Bean class and it can be visually represented as below:

Essentially, MVC1, followed by its innate structure, incurred low extensibility and maintainability issues. Hence, MVC1 was soon replaced by MVC2.

MVC1 Code

<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<html>
<head>
    <title>User Info</title>
</head>
<body>

<%-- Controller Part --%>
<%
    // Simulate business logic (Model) directly in JSP
    String name = "Alice";
    String email = "alice@example.com";
%>

<%-- View Part --%>
<h1>User Information</h1>
<p>Name: <%= name %></p>
<p>Email: <%= email %></p>

</body>
</html>

☁️ MVC2

☁️ The MVC2 pattern refers to a design pattern where the Model, View, and Controller is both logically and physically separated.

MVC2 was introduced to resolve the issues present in MVC1 by clearly defining boundaries for each component, which are:

  • model: Service and Java Bean class.
  • view: JSP files.
  • controller: Servlet class.

With these distinct boundaries, MVC2 provides a more modular, maintainable, and testable structure compared to MVC1, making it easier for developers to build scalable applications.

The MVC2 can be visualised as below:

MVC2 Code

Model

// User.java (Model)
public class User {
    private String name;
    private String email;

    public User(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public String getEmail() {
        return email;
    }
}

View

<!-- userInfo.jsp (View) -->
<html>
<head>
    <title>User Info</title>
</head>
<body>
    <h1>User Information</h1>
    <p>Name: ${name}</p>
    <p>Email: ${email}</p>
</body>
</html>

Controller

// UserController.java (Controller)
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/user")
public class UserController extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        // Simulate fetching data from a database or other business logic
        User user = new User("Alice", "alice@example.com");
        
        // Set data as request attributes (View part tightly coupled here)
        request.setAttribute("name", user.getName());
        request.setAttribute("email", user.getEmail());

        // Forward to the JSP (View)
        request.getRequestDispatcher("userInfo.jsp").forward(request, response);
    }
}

🌿 Spring MVC

🌿 Spring MVC is an MVC pattern that is particularly based on the MVC2 pattern.

Spring MVC specifically introduces the Front Controller pattern where all HTTP requests are managed centrally by the Dispatcher Servlet.

Specifically, for the incoming HTTP requests, Tomcat via its Servlet Container forwards all the HTTP requests to the Dispatcher Servlet. The Dispatcher Servlet then finds a relevant Spring Bean (Controller@method) from its HandlerMapping field and passes the found Spring Bean to the Handle Adapter where it finds the runnable adapter of the handler then processes the requests through services and repositories if they are implemented in the controller.

Adapter then returns the ModelAndView the, processed result, and the Dispatcher Servlet then forwards the result to the ViewResolver where it returns the View instance as a response where it is further processed into a JSP with relevant dynamic datasets that should be rendered in the JSP.

How to doin Java Available at here


Like MVC2, Spring MVC, can be largley divided into three components mostly provided in spring annotations:

  • model: @Service, @Repository
  • controller: @Controller
  • view: JSP

Spring MVC

Model

public class User {
    private String name;
    private int age;

    // Constructors, Getters, and Setters
    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

View

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>User Info</title>
</head>
<body>
    <h1>User Details</h1>
    <p>Name: <span th:text="${user.name}"></span></p>
    <p>Age: <span th:text="${user.age}"></span></p>
</body>
</html>

Controller

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class UserController {

    @GetMapping("/user")
    public String getUser(Model model) {
        // Create a new user object
        User user = new User("John Doe", 30);

        // Add user object to the model
        model.addAttribute("user", user);

        // Return the name of the view (Thymeleaf template)
        return "userView";  // this corresponds to userView.html in templates folder
    }
}

πŸ“š References

JSP2.3 μ›Ή ν”„λ‘œκ·Έλž˜λ°
Spring Doc
F-Lab (1)
F-Lab (2)
How to doin Java

profile
Hello

0개의 λŒ“κΈ€