Controller in Java

In Java, particularly within the Spring framework, a "controller" is a fundamental component that plays a crucial role in handling user interactions and managing the flow of data between the user interface and the back-end services. Controllers are responsible for processing incoming requests, invoking business logic, and returning the appropriate responses. They are a key part of the Model-View-Controller (MVC) architecture, which promotes a clean separation of concerns within an application.

Controller in Spring Boot

A controller in Spring Boot is a central piece of the Spring MVC framework. It is responsible for handling user requests and invoking back-end business services. The controller prepares the model with data for the views to render in the UI, acting as an intermediary between the view and the model. This separation of concerns allows for a clean architecture.

Example of a Simple Controller

To illustrate the use of a controller, consider a scenario where you need to render the logged-in user's name in the UI. In your controller, you can add the userName as a key, and the user's name as the value. The following listing demonstrates how to define an HTTP endpoint using @GetMapping and populate the model with values:

@GetMapping                                           
public String getLoggedInUserName(Model model) {
    model.addAttribute("userName", user.getName());    
    return "index";                                    
}

The associated HTML code to display the value of the userName attribute is: Logged In user: <span th:text="${userName}" />. The userName value from the model is rendered in the UI by the key name you have specified.

CourseController: A Comprehensive Example

The CourseController class provides a more comprehensive example of a Spring controller, supporting CRUD operations for a course management application. The following listing shows the CourseController class:

package com.manning.sbip.a02.controller;

import com.manning.sbip.a02.model.Course;
import com.manning.sbip.a02.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Collections;
import java.util.List;

@Controller
public class CourseController {

    private final CourseService courseService;
    @Autowired
    public CourseController(CourseService courseService) {                  
        this.courseService = courseService;
    }

    @GetMapping("/")
    public String index() {
        return "redirect:/index";
    }

    @GetMapping("/index")
    public String index(Model model) {                                      
        List<Course> courseList = (List<Course>) courseService.findAllCourses();
        model.addAttribute("courses", courseList.isEmpty() ? Collections.EMPTY_LIST : courseList);
        return "index";
    }

    @GetMapping("/addcourse")
    public String showAddCourseForm(Course course) {                        
        return "add-course";
    }

    @PostMapping("/addcourse")
    public String addCourse(@Valid Course course, BindingResult result, Model model){                                                            
        if (result.hasErrors()) {
            return "add-course";
        }
        model.addAttribute("courses", courseService.createCourse(course));
        return "redirect:/index";
    }

    @GetMapping("/update/{id}")
    public String showUpdateCourseForm(@PathVariable("id") long id, Model model) {                                                                 
        model.addAttribute("course", courseService.findCourseById(id).get());
        return "update-course";
    }

    @PutMapping("/update/{id}")
    public String updateCourse(@PathVariable("id") long id, @Valid Course course, BindingResult result, Model model) {                             
        if (result.hasErrors()) {
            course.setId(id);
            return "update-course";
        }
        model.addAttribute("courses", courseService.updateCourse(course));
        return "redirect:/index";
    }

    @DeleteMapping("/delete/{id}")
    public String deleteCourse(@PathVariable("id") long id, Model model) {  
        model.addAttribute("courses", courseService.deleteCourseById(id));
        return "redirect:/index";
    }
}

Key Points

  • Dependency Injection: The CourseController uses dependency injection to obtain an instance of CourseService, which is used to perform CRUD operations.
  • HTTP Endpoints: The controller defines several HTTP endpoints using annotations like @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping to handle different operations.
  • Model and View: The controller methods interact with the model to add attributes that are rendered in the view. For example, the index method adds a list of courses to the model, which is then displayed on the index page.

Thymeleaf Integration

The controller interacts with Thymeleaf templates to render the UI. For instance, the index.html page uses Thymeleaf tags to display a list of courses:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Courses</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
</head>
<body>
<div th:switch="${#lists.size(courses)}" class="container my-5">
    <div class="row">
        <div class="col-md-2"></div>
        <div class="col-md-8">

            <div th:case="'0'">
                <h2>You haven't added any course yet!</h2>
                <p class="text-success">Add a course by clicking below!</p>
            </div>
            <div th:case="*">
                <h2 class="my-5">Courses</h2>
                <table class="table table-striped table-responsive-md">
                    <thead>
                    <tr>
                        <th>Course Name</th>
                        <th>Course Category</th>
                        <th>Course Rating</th>
                        <th>Course Description</th>
                        <th>Edit</th>
                        <th>Delete</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr th:each="course : ${courses}">
                        <td th:text="${course.name}"></td>
                        <td th:text="${course.category}"></td>
                        <td th:text="${course.rating}"></td>
                        <td th:text="${course.description}"></td>
                        <td><a th:href="@{/update/{id}(id=${course.id})}" class="btn btn-primary"><i class="fas fa-edit"></i></a></td>
                        <td>
                            <form action="#" th:action="@{/delete/{id}(id=${course.id})}" th:method="delete">
                                <button type="submit" class="btn btn-danger">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </form>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
            <p class="my-5"><a href="/addcourse" class="btn btn-primary"><i class="fas fa-plus-square"></i></a></p>
        </div>
        <div class="col-md-2"></div>
    </div>
</div>
</body>
</html>

This integration allows for dynamic content rendering based on the data provided by the controller, enhancing the user experience by providing real-time updates and interactions.

[Controller in Spring Microservices](https://livebook.manning.com/book/spring-microservices-in-action/chapter-2/140)

In a Spring Boot application, a controller is a pivotal component responsible for handling incoming HTTP requests and mapping them to appropriate Java methods. This is achieved through the use of the @RestController annotation, which not only designates the class as a controller but also facilitates the automatic serialization and deserialization of JSON data. This means that the controller can seamlessly convert Java objects to JSON and vice versa, making it easier to handle web requests and responses.

Defining Endpoints

Controllers define endpoints using the @RequestMapping annotations. These annotations are used to map specific HTTP requests to particular methods within the controller. By doing so, they establish a clear and organized way to handle different types of requests, such as GET, POST, PUT, and DELETE, each corresponding to a specific method in the controller.

The use of @RequestMapping allows developers to specify the URL patterns and the HTTP methods that a particular method should respond to. This provides a flexible and powerful mechanism to define the behavior of the application in response to various web requests.

In summary, controllers in Spring Boot applications serve as the bridge between incoming HTTP requests and the business logic of the application, ensuring that requests are processed efficiently and responses are generated in a format that clients can easily consume.

For more detailed information, you can refer to the Spring Boot in Practice and Spring Microservices in Action books.

| Book Title | Usage of Controller | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|---------------------|-----------------|-------------------------------|---------------|-----------------------|
| [Spring Boot in Practice](https://www.manning.com/books/spring-boot-in-practice) | Discusses the role of controllers in handling user requests and preparing models for views. Emphasizes separation of concerns. | Provides detailed examples of CRUD operations using `CourseController`. | Connects controllers with dependency injection, HTTP endpoints, and Thymeleaf integration. | Includes code snippets for simple and comprehensive controller examples. | Demonstrates practical use in a course management application. [more](https://www.manning.com/books/spring-boot-in-practice) |
| [Spring Microservices in Action](https://www.manning.com/books/spring-microservices-in-action) | Highlights the use of `@RestController` for handling HTTP requests and JSON serialization/deserialization. | Focuses on defining endpoints with `@RequestMapping` and handling different HTTP methods. | Explains the role of controllers in the context of microservices architecture. | Provides an overview of endpoint definition and request handling. | Illustrates the controller's role in bridging HTTP requests with business logic. [more](https://www.manning.com/books/spring-microservices-in-action) |

FAQ (Frequently asked questions)

How is a controller annotated in Spring Boot?

How are endpoints defined in a Spring Boot controller?