DEV Community

Cover image for Spring Boot Controllers Basics
Pete
Pete

Posted on

Spring Boot Controllers Basics

In Spring Boot, a controller is a class that contains methods that process HTTP requests. A controller is created by annotating a class with RestController.

@RestController
public class ExampleController {
    private ExampleRepository exampleRepository;
    private static final String template = "Hello, %s!";

    @GetMapping("/examples/{requestedId}")
    public ResponseEntity<Example> findById(@PathVariable Long requestedId) {
    }
}
Enter fullscreen mode Exit fullscreen mode

The GetMapping annotation is used to route all GET requests that match a string pattern to a method in a controller. In the code example you just looked at, the GetMapping annotation was used to route all GET requests to the URL /examples/* to the findById method. With this code, when a request is sent to /examples/, the findById method will be called.

RequestMapping

There are other annotations for other request methods like PostMapping and DeleteMapping. They are all derived from the parent annotation RequestMapping and you can use RequestMapping in their place, although, when you use RequestMapping you have to specify the HTTP method it is supposed to handle

@RestController
public class ExampleController {
    private ExampleRepository exampleRepository;
    private static final String template = "Hello, %s!";

    @RequestMapping(method="GET", path="/examples/{requestedId}")
    public ResponseEntity<Example> findById(@PathVariable Long requestedId) {
    }
}
Enter fullscreen mode Exit fullscreen mode

RequestMapping is most commonly used to specify the URLs that you want a RestController to handle.

@RestController
@RequestMapping("/api/v1/examples")  // This is the base path
public class ExampleController {
    @GetMapping
    public String getAllExamples() {
    }

    @GetMapping("/{id}")
    public String getExampleById(@PathVariable("id") Long id) {
    }

    @PostMapping
    public String createExample() {
    }

    @DeleteMapping("/{id}")
    public String deleteExample(@PathVariable("id") Long id) {
    }
}
Enter fullscreen mode Exit fullscreen mode

In the code snippet above, by annotating the RestController class with RequestMapping, the url /api/v1/examples acts as a prefix for all the routes within the class. This means the getExampleById method that has a GetMapping of /{id} actually has a GetMapping of /api/v1/examples/{id} and the same applies to every single method in this class that has a RequestMapping associated with it.

Top comments (0)