Spring MVC Tutorial

Core Spring MVC

Spring MVC - Annotation

Spring MVC - Form Handling

Spring MVC with JSTL

Spring MVC with REST API

Spring MVC with Database

How to Create Your First Model in Spring MVC?

Creating a model in Spring MVC usually refers to creating a Java class (often annotated with @Entity for persistence with JPA) that represents data in your application. The model forms the 'M' in the MVC (Model-View-Controller) pattern used by Spring MVC.

Here's a step-by-step guide to create your first model in Spring MVC:

1. Set Up a Spring MVC Project:

If you haven't set up a Spring project yet, the easiest way is to use Spring Initializr. Select the dependencies you need; at a minimum, you'd select "Spring Web" for a web application.

2. Define the Model Class:

Let's say you want to model a Book entity. Create a new Java class in your project:

public class Book {

    private Long id;
    private String title;
    private String author;
    private String isbn;

    // Default and parameterized constructors, getters, setters, etc.

}

3. (Optional) Add JPA Annotations for Persistence:

If you want to store instances of your model in a database using Spring Data JPA, you need to add additional annotations:

  • Add the "Spring Data JPA" dependency using Initializr or manually in your pom.xml or build.gradle:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
  • Annotate your model:
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

@Entity
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;
    private String author;
    private String isbn;

    // Getters, setters, etc.
}

4. Use the Model in Your Application:

You can now use the Book model class in various parts of your application:

  • In controllers, to capture data from forms or display data.
  • In services, to apply business logic.
  • In repositories, to save and retrieve data (if using JPA).

Example:

@RestController
public class BookController {

    @GetMapping("/book")
    public Book getSampleBook() {
        return new Book(1L, "Spring MVC Guide", "John Doe", "123456789");
    }
}

This simple controller would return a JSON representation of a book when you access the /book endpoint.

Conclusion:

Creating a model in Spring MVC primarily involves defining a Java class that represents your data. You can then leverage this model throughout your application. If you want to persist instances of your model to a database, Spring Data JPA provides powerful, easy-to-use tools to help.

  1. Creating a model in Spring MVC example:

    Description: In Spring MVC, a model represents the data that will be presented to the user. The model is usually created and populated in a controller method and then passed to the view for rendering.

    Code snippet (Java):

    @Controller
    @RequestMapping("/example")
    public class ExampleController {
    
        @GetMapping("/showData")
        public String showData(Model model) {
            // Creating a model and adding attributes
            model.addAttribute("message", "Hello, Spring MVC!");
            model.addAttribute("count", 42);
    
            // Returning the view name
            return "showDataView";
        }
    }
    

    Code snippet (HTML - Thymeleaf template):

    <!-- Thymeleaf template to display model attributes -->
    <html>
    <body>
        <h2 th:text="${message}"></h2>
        <p th:text="${'Count: ' + count}"></p>
    </body>
    </html>
    
  2. Your first Spring MVC model step-by-step:

    Description: A step-by-step guide to creating your first Spring MVC model involves defining a controller method, creating a model, adding attributes, and returning the view name.

    Code snippet (Java):

    @Controller
    @RequestMapping("/first")
    public class FirstController {
    
        @GetMapping("/welcome")
        public String welcome(Model model) {
            // Creating a model and adding attributes
            model.addAttribute("greeting", "Welcome to Spring MVC!");
            model.addAttribute("username", "User123");
    
            // Returning the view name
            return "welcomeView";
        }
    }
    

    Code snippet (HTML - Thymeleaf template):

    <!-- Thymeleaf template to display model attributes -->
    <html>
    <body>
        <h2 th:text="${greeting}"></h2>
        <p th:text="${'Hello, ' + username + '!'}"></p>
    </body>
    </html>
    
  3. Introduction to Spring MVC model creation:

    Description: An introduction to Spring MVC model creation involves understanding the role of the Model interface, which is used to pass data from the controller to the view.

    Code snippet (Java):

    @Controller
    @RequestMapping("/intro")
    public class IntroController {
    
        @GetMapping("/display")
        public String displayData(Model model) {
            // Creating a model and adding attributes
            model.addAttribute("title", "Introduction to Spring MVC Models");
            model.addAttribute("author", "John Doe");
    
            // Returning the view name
            return "displayView";
        }
    }
    

    Code snippet (HTML - Thymeleaf template):

    <!-- Thymeleaf template to display model attributes -->
    <html>
    <body>
        <h2 th:text="${title}"></h2>
        <p th:text="${'Author: ' + author}"></p>
    </body>
    </html>
    
  4. How to use models in Spring MVC:

    Description: Models in Spring MVC are used to carry data from the controller to the view. They can be created as method parameters in controller methods, and attributes can be added to them.

    Code snippet (Java):

    @Controller
    @RequestMapping("/use")
    public class UseController {
    
        @GetMapping("/displayData")
        public String displayData(Model model) {
            // Creating a model and adding attributes
            model.addAttribute("name", "John");
            model.addAttribute("age", 30);
    
            // Returning the view name
            return "displayDataView";
        }
    }
    

    Code snippet (HTML - Thymeleaf template):

    <!-- Thymeleaf template to display model attributes -->
    <html>
    <body>
        <p th:text="${'Name: ' + name}"></p>
        <p th:text="${'Age: ' + age}"></p>
    </body>
    </html>
    
  5. Working with models in Spring MVC applications:

    Description: Working with models involves creating, populating, and using models in Spring MVC controllers to provide data to the views.

    Code snippet (Java):

    @Controller
    @RequestMapping("/work")
    public class WorkController {
    
        @GetMapping("/employeeInfo")
        public String employeeInfo(Model model) {
            // Creating a model and adding attributes
            model.addAttribute("employeeName", "Alice");
            model.addAttribute("designation", "Software Engineer");
    
            // Returning the view name
            return "employeeInfoView";
        }
    }
    

    Code snippet (HTML - Thymeleaf template):

    <!-- Thymeleaf template to display model attributes -->
    <html>
    <body>
        <p th:text="${'Employee: ' + employeeName}"></p>
        <p th:text="${'Designation: ' + designation}"></p>
    </body>
    </html>
    
  6. Creating and using models in Spring MVC controllers:

    Description: This involves creating models in Spring MVC controllers and using them to pass data to the views for rendering.

    Code snippet (Java):

    @Controller
    @RequestMapping("/create")
    public class CreateController {
    
        @GetMapping("/bookInfo")
        public String bookInfo(Model model) {
            // Creating a model and adding attributes
            model.addAttribute("bookTitle", "Spring MVC in Action");
            model.addAttribute("authorName", "Craig Walls");
    
            // Returning the view name
            return "bookInfoView";
        }
    }
    

    Code snippet (HTML - Thymeleaf template):

    <!-- Thymeleaf template to display model attributes -->
    <html>
    <body>
        <p th:text="${'Book: ' + bookTitle}"></p>
        <p th:text="${'Author: ' + authorName}"></p>
    </body>
    </html>
    
  7. Example of building a model in Spring MVC:

    Description: An example demonstrating the complete process of building a model in a Spring MVC controller and using it to display data in a view.

    Code snippet (Java):

    @Controller
    @RequestMapping("/example")
    public class ExampleController {
    
        @GetMapping("/showInfo")
        public String showInfo(Model model) {
            // Creating a model and adding attributes
            model.addAttribute("productName", "Spring MVC Essentials");
            model.addAttribute("category", "Programming");
    
            // Returning the view name
            return "showInfoView";
        }
    }
    

    Code snippet (HTML - Thymeleaf template):

    <!-- Thymeleaf template to display model attributes -->
    <html>
    <body>
        <p th:text="${'Product: ' + productName}"></p>
        <p th:text="${'Category: ' + category}"></p>
    </body>
    </html>