Building a powerful RESTful API: Comparison and application of @RestController and @Controller

Preface

Have you ever thought about how the background processes requests and generates responses when you browse the web or call an API? This is the task of Spring MVC. In this blog, we will take you into the wonderful world of Spring MVC and explore in depth the @RestControllerworking principles and usage of , @Controllerand @ResponseBodyannotations. Whether you are a beginner or an experienced developer, this article will provide you with clear guidelines to help you build powerful web applications and RESTful APIs.

What is RESTful API

RESTful API (Representational State Transfer API) is an application programming interface based on REST architectural style. It is a design philosophy that aims to make web applications simpler, scalable, and easier to understand. The core idea of ​​RESTful API is to use resources as the core concept and operate resources through standard HTTP methods.

The following are the main features and concepts about RESTful API:

  1. Resource : In RESTful API, everything is a resource. Resources can be actual data objects or virtual concepts, such as users, products, orders, etc. Each resource has a unique identifier (usually a URL).

  2. HTTP methods : RESTful API uses standard HTTP methods to perform operations. The most commonly used HTTP methods include:

    • GET : Used to retrieve information about a resource.
    • POST : used to create new resources.
    • PUT : used to update existing resources.
    • DELETE : used to delete resources.
  3. Statelessness : RESTful APIs are stateless, and each request contains enough information for the server to understand and process the request without relying on the status of previous requests. This makes API design simpler and scalable.

  4. URL as resource identifier : Each resource is represented by a unique URL identifier. Through URLs, clients can access and operate resources.

  5. Using HTTP status codes : HTTP status codes are used to indicate the success or failure of a request and the reason for the failure. Common status codes include 200 (success), 201 (created), 404 (not found), 500 (server error), etc.

  6. Data format : RESTful APIs typically use standard data formats such as JSON or XML to pass data. These formats are easy to parse and generate while providing good readability.

  7. No need to save state (Stateless) : RESTful API does not need to save the client's state information on the server side. Each request should contain enough information so that the server can understand and process the request.

  8. Scalability : Due to the stateless and resource-oriented nature of RESTful APIs, they generally have good scalability and can handle high loads and large-scale usage.

  9. Security : RESTful APIs can use standard HTTP security mechanisms (such as HTTPS) to protect communications, and can use authentication and authorization mechanisms to restrict access to resources.

In summary, a RESTful API is an API designed and built using the HTTP protocol and REST principles. Its goal is to make Web services simpler, easier to understand, and scalable. Due to its widespread adoption and standardization, RESTful APIs have become a common way to build modern web applications and mobile applications.

@RestController,@Controller,@ResponseBody

@RestController, @Controller and @ResponseBody are commonly used annotations in the Spring framework for building RESTful web applications. Their usage and meaning are explained in detail below:

1. @ControllerNotes:

  • Meaning: @ControllerAnnotations are used to identify a class as a controller in Spring MVC. The controller is responsible for processing the client's request and calling the corresponding method based on the requested information to process the request and generate a response.
  • Usage: You need to place this annotation in front of a class to indicate that this class is a controller. Typically, you will also need to use additional annotations at the method level to specify which methods are used to handle specific requests.

2. @RestControllerNotes:

  • Meaning: @RestControllerAn annotation is @Controllera specialized version of , which combines the functionality @Controllerof @ResponseBody. It means that each method of this class will return an object instead of a view, and these objects will be automatically serialized into JSON or XML and then sent to the client.
  • Usage: @ControllerSimilar to , you need to place this annotation in front of a class to indicate that this class is a REST controller. You can then use @RequestMappingthe etc annotation at the method level to specify methods for handling different HTTP requests.

3. @ResponseBodyNotes:

  • Meaning: @ResponseBodyThe annotation is used to indicate that the return value of a method should be written directly into the HTTP response body instead of being parsed into a view. This is typically used to return responses in JSON, XML, or other data formats.
  • Usage: You can @ResponseBodyplace annotations in front of a method to indicate that the return value of this method will be directly used as the content of the HTTP response. Typically, you need to use the etc annotation on the method @RequestMappingto specify the requested URL and HTTP method.

Example

Non-thymeleaf example implementation

Here is an example demonstrating how to use these annotations in a Spring controller:

@RestController
@RequestMapping("/api")
public class MyRestController {
    
    
    
    @GetMapping("/hello")
    public String sayHello() {
    
    
        return "Hello, World!";
    }
    
    @PostMapping("/add")
    public ResponseEntity<String> addData(@RequestBody DataObject data) {
    
    
        // 处理请求并返回响应
        return ResponseEntity.ok("Data added successfully");
    }
}

In the above example, @RestControllerthe annotation indicates MyRestControllera REST controller, @GetMappingand @PostMappingthe annotation specifies different HTTP request processing methods, and @ResponseBodythe annotation is used to return data written directly into the HTTP response body. At the same time, @RequestMappingthe annotation defines the URL mapping path.

thymeleaf example implementation

Now, let's create an example in conjunction with Thymeleaf:

First, make sure the Thymeleaf template engine is configured in your project. Then, create a Spring MVC controller as follows:

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MyController {
    
    

    @GetMapping("/hello")
    public String sayHello(Model model) {
    
    
        model.addAttribute("message", "Hello, World!");
        return "hello"; // 这里返回的是Thymeleaf模板的名称
    }
}

In the above example, @Controllerthe annotation identifies MyControllerthe class as a controller and @GetMapping("/hello")the annotation maps /hellothe GET request to the path. In sayHellothe method, we use Modelthe object to pass data to the view.

Next, create a Thymeleaf template, assuming the template file is named hello.html, and place it in the appropriate template directory:

<!DOCTYPE html>
<html>
<head>
    <title>Hello Page</title>
</head>
<body>
    <h1 th:text="${message}"></h1>
</body>
</html>

In this template, we use Thymeleaf's syntax to render messages passed from the controller.

Finally, make sure your Spring configuration is correct, including Thymeleaf’s template parser configuration. This way, when the user accesses /hellothe path, Spring MVC will call sayHellothe method, render the Thymeleaf template, and pass the message into the template.

This example demonstrates how to combine Spring MVC annotations and the Thymeleaf template engine to create a simple web application. Make sure to configure and scale according to your project needs.

Guess you like

Origin blog.csdn.net/Mrxiao_bo/article/details/133487163