Controller Layer

In Spring MVC, the controller layer is the top layer of the architecture that is used to handle web requests. Then depending on the type of request, it passed it to corresponding layers.

Annotations used:

  • @Controller – This annotation marks that the particular class serves the role of a controller.
  • @GetMapping – This annotation marks the mapping of HTTP GET requests onto specific handler methods.
  • @PostMapping – This annotation marks the mapping of HTTP POST requests onto specific method handlers.

Java




import com.example.testing_001.model.Course;
import com.example.testing_001.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
 
import java.util.List;
 
@Controller
public class CourseController {
 
    @Autowired
    private CourseService courseService;
 
    @GetMapping("/")
    public String viewHomePage(Model model) {
        return findPaginated(1, "courseName", "asc", model);
    }
 
    @GetMapping("/add")
    public String showNewCourseForm(Model model) {
        Course Course = new Course();
        model.addAttribute("course", Course);
        return "new_course";
    }
 
    @PostMapping("/save")
    public String saveCourse(@ModelAttribute("course") Course course) {
        // save Course to database
        courseService.saveCourse(course);
        return "redirect:/";
    }
 
    @GetMapping("/update/{id}")
    public String showFormForUpdate(@PathVariable( value = "id") long id, Model model) {
 
        Course course = courseService.getCourseById(id);
        model.addAttribute("course", course);
        return "update_course";
    }
 
    @GetMapping("/delete/{id}")
    public String deleteCourse(@PathVariable (value = "id") long id) {
 
        this.courseService.deleteCourseById(id);
        return "redirect:/";
    }
 
 
    @GetMapping("/page/{pageNo}")
    public String findPaginated(@PathVariable (value = "pageNo") int pageNo,
                                @RequestParam("sortField") String sortField,
                                @RequestParam("sortDir") String sortDir,
                                Model model) {
        int pageSize = 5;
 
        Page<Course> page = courseService.findPaginated(pageNo, pageSize, sortField, sortDir);
        List<Course> listCourses = page.getContent();
 
        model.addAttribute("currentPage", pageNo);
        model.addAttribute("totalPages", page.getTotalPages());
        model.addAttribute("totalItems", page.getTotalElements());
 
        model.addAttribute("sortField", sortField);
        model.addAttribute("sortDir", sortDir);
        model.addAttribute("reverseSortDir", sortDir.equals("asc") ? "desc" : "asc");
 
        model.addAttribute("listCourses", listCourses);
        return "index";
    }
}


TRY: Change the GET mapping for course update and delete course to PUT mapping and DELETE mapping respectively. It is considered best practice to use mappings based on the functionality of the api.

Spring MVC CRUD with Example

CRUD stands for Create, Read/Retrieve, Update, and Delete. These are the four basic operations to create any type of project. Spring MVC is a Web MVC Framework for building web applications. It is a spring module same as Spring boot, spring-security, etc. The term MVC stands for Model-View-Controller architecture. In this article, we will be building a simple course-tracking CRUD application that will be focused on the Spring MVC module.

Similar Reads

CRUD Example of Spring MVC

Project Structure...

1. Add Dependencies to build.gradle file

Add the following dependencies to build.gradle file if not already present....

2. Model Layer

Create a simple POJO (Plain old java object) with some JPA and Lombok annotations....

3. DAO (Data access object) / Repository Layer

...

4. Service Layer

@Repository: This annotation is a stereotype that marks the repository class. It indicates that the annotated class acts as a database on which CRUD operations can take place. JpaRepository : JpaRepository is a JPA-specific extension of the Repository. It contains the full API of CrudRepository and PagingAndSortingRepository. So it contains API for basic CRUD operations and also API for pagination and sorting. Here we enable database operations for Employees. To learn more about spring data Jpa, refer this article....

5. Controller Layer

...

HTML Templates

The service layer provides an abstraction over the data layer. Its main purpose is to fulfill business requirements. It is always better to separate business logic from app logic....

CRUD Operations

...

Contact Us