Code example of Controller in SpringBoot project

In Spring Boot, Controller is the component responsible for processing HTTP requests and returning HTTP responses. We can create a Controller by adding annotations like @Controller, @RestController to the class. Here is a simple sample code:

@RestController
@RequestMapping("/users")
public class UserController {
    
    @Autowired
    private UserService userService;

    @GetMapping("/")
    public List<User> findAllUsers() {
        return userService.findAllUsers();
    }

    @GetMapping("/{id}")
    public User findUserById(@PathVariable Long id) {
        return userService.findUserById(id);
    }

    @PostMapping("/")
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }

    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User user) {
        return userService.updateUser(id, user);
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
    }
}

The preceding code defines a UserControllerController class named that maps to /usersthe path to handle user-related CRUD operations.

  • findAllUsers() The method is used to get a list of all users and return a list containing all users;
  • findUserById() The method finds the user according to the user's ID and returns the user's information;
  • createUser() The method is used to create a new user, the request body carries the user information, and returns the successfully created user information;
  • updateUser() The method is used to update user information, query the corresponding user according to the user ID, update the user information in the request body to the database, and return the updated user information;
  • deleteUser() method deletes a user based on the user's ID.

It should be noted that a business logic service class named is used in the above code UserService to handle user-related business logic, such as database operations, data validation, and so on. This class needs to be @Serviceannotated and injected into the Controller.

When we send GET, POST, PUT and DELETE requests to the path in the browser or other clients /users, Spring Boot will automatically distribute the requests to the corresponding Controller methods, perform corresponding operations in the methods, and encapsulate the results into HTTP The response is returned to the client.

Guess you like

Origin blog.csdn.net/Kristabo/article/details/130695661