Topic 9 – MVC Framework Module

image 2

Play Store Application link – Spring Framework in 9 steps – Apps on Google Play

The Spring MVC framework helps build web applications using the Model-View-Controller (MVC) pattern, which separates an application into three parts:

  1. Model: Represents the application’s data and business logic.
  2. View: Renders data for the user (e.g., web pages).
  3. Controller: Handles user input and updates the Model and View.

Github Project link (XML based) – https://github.com/kuldeep101990/SpringMVCXml

Github Project link (Annotation based) – https://github.com/kuldeep101990/SpringMVCAnnotation

Example: Spring MVC in Action

Let’s look at a basic Spring MVC example.

1. Controller Example

@Controller
public class MyController {
    @GetMapping("/") // Maps to the root URL
    public String root() {
        // Returns the logical view name "home.jsp"
        return "home";
    }
    @GetMapping("/greet") // Maps to "/greet"
    public String greet(@RequestParam(name = "name", defaultValue = "Guest") String name, Model model) {
        // Adds the "name" to the Model
        model.addAttribute("name", name);
        // Returns the logical view name "greet.jsp"
        return "greet";
    }
    @GetMapping("/user") // Maps to "/user"
    public String user(Model model) {
        // Creates a User object as the Model
        User user = new User("John", "Doe");
        // Adds the "user" to the Model
        model.addAttribute("user", user);
        // Returns the logical view name "user.jsp"
        return "user";
    }
}

2. Model example

public class User {
    private String firstName;
    private String lastName;
    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    public String getFirstName() {
        return firstName;
    }
    public String getLastName() {
        return lastName;
    }
}

3. JSP View Example (home.jsp)

<html>
<head>
    <title>Spring MVC Home</title>
</head>
<body>
    <h1>Welcome to Spring MVC Framework!</h1>
    <p><a href="${pageContext.request.contextPath}/greet">Greet</a> | <a href="${pageContext.request.contextPath}/user">User Info</a></p>
</body>
</html>


Conclusion

The Spring MVC framework simplifies web development by clearly separating concerns:

  • Controllers handle requests.
  • Models contain data.
  • Views render the data to the user.

By configuring basic components like the Controller and ViewResolver, you can easily build a fully functional Spring MVC web application.


Leave a Reply

Your email address will not be published. Required fields are marked *