DEV Community

DevCorner
DevCorner

Posted on

MVC Pattern in Spring MVC with a Blog Example

The Model-View-Controller (MVC) pattern is a design pattern that separates an application into three components:

  • Model → Represents the data and business logic.
  • View → Handles the UI/Presentation layer.
  • Controller → Handles user requests, processes them, and sends data to the view.

Spring MVC follows this pattern to build web applications in a structured and maintainable way. Let’s understand this with a blog application example where users can create, view, and manage blog posts.


1. Components of MVC in a Spring MVC Blog

1.1 Model (Data + Business Logic)

The Model represents the blog post data and handles business logic. In Spring MVC, it is typically implemented using Java classes (POJOs), JPA/Hibernate entities, and Service Layer.

Example: BlogPost Model

@Entity
public class BlogPost {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String content;
    private LocalDateTime createdAt;

    // Constructors, Getters, Setters
}
Enter fullscreen mode Exit fullscreen mode

1.2 View (User Interface)

The View is responsible for rendering the response. In Spring MVC, the view is typically implemented using Thymeleaf, JSP, or other frontend technologies like React/Angular.

Example: Thymeleaf View (blog.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Blog Posts</title>
</head>
<body>
    <h1>All Blog Posts</h1>
    <ul>
        <li th:each="post : ${posts}">
            <h2 th:text="${post.title}"></h2>
            <p th:text="${post.content}"></p>
            <p><i>Published on: <span th:text="${post.createdAt}"></span></i></p>
        </li>
    </ul>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

1.3 Controller (Handles Requests)

The Controller manages incoming HTTP requests, processes data using the Model, and returns the appropriate View. In Spring MVC, controllers are implemented using @Controller or @RestController annotations.

Example: BlogController

@Controller
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    private BlogService blogService;

    // Show all blog posts
    @GetMapping
    public String listPosts(Model model) {
        List<BlogPost> posts = blogService.getAllPosts();
        model.addAttribute("posts", posts);
        return "blog"; // Refers to blog.html
    }

    // Show the form to create a new post
    @GetMapping("/new")
    public String newPostForm(Model model) {
        model.addAttribute("blogPost", new BlogPost());
        return "newPost"; // Refers to newPost.html
    }

    // Handle form submission for new post
    @PostMapping
    public String savePost(@ModelAttribute BlogPost blogPost) {
        blogService.savePost(blogPost);
        return "redirect:/blog"; // Redirect to list all posts
    }
}
Enter fullscreen mode Exit fullscreen mode

2. How MVC Works in Spring MVC (Request Flow)

Example Scenario: A User Requests a Blog Post List

  1. User sends a request to /blog

    GET /blog request is sent to BlogController.

  2. Controller Processes Request

    listPosts(Model model) method fetches blog posts from BlogService.

  3. Model Passes Data to View

    model.addAttribute("posts", posts); sends blog data to the view.

  4. View Displays Data

    blog.html renders the list of blog posts with Thymeleaf.


3. Advantages of Using MVC in Spring MVC

Separation of Concerns – Keeps business logic (Model), request handling (Controller), and UI (View) separate.

Scalability – New features can be added easily.

Maintainability – Easier to debug and update code.

Reusable Components – Models and Views can be reused across multiple controllers.


Final Thoughts

Spring MVC provides a structured way to develop web applications using the MVC pattern. In a blog application, the Model (BlogPost) handles data, the View (Thymeleaf/JSP) renders UI, and the Controller (BlogController) processes requests. This architecture makes the application clean, maintainable, and scalable. 🚀

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay