Sobes.tech
Junior

How to create a controller in Spring?

sobes.tech AI

Answer from AI

  1. Create a class and annotate it with @Controller (for MVC) or @RestController (for REST).
  2. Inside the class, define methods to handle HTTP requests.
  3. Annotate these methods with mapping annotations, such as @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @RequestMapping, specifying access paths.
  4. Inside the methods, write the logic for processing the request and returning a response.

Example with @RestController:

// Used for creating RESTful web services.
// Includes @Controller and @ResponseBody.
@RestController
@RequestMapping("/users") // Base path for all endpoints in this controller
public class UserController {

    // Method to handle GET requests to /users.
    @GetMapping
    public List<User> getAllUsers() {
        // Logic to get all users
        return // list of users;
    }

    // Method to handle GET requests to /users/{id}.
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        // Logic to get user by id
        return // user;
    }

    // Method to handle POST requests to /users.
    @PostMapping
    public ResponseEntity<User> createUser(@RequestBody User user) {
        // Logic to create a new user
        User createdUser = // created user;
        // Return status 201 Created
        return ResponseEntity.status(HttpStatus.CREATED).body(createdUser);
    }
}
How to create a controller in Spring? — Java - sobes.tech