AI Hints
Home›Spring Boot Tutorial›Testing with curl, @RestController and @GetMapping
Spring Boot · Lesson 14 of 120

@RestController

Classes that answer.

⏱ 2 min read▶ Video at 17:57🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

We've used at Rest Controller a few times. Let's see what it really does, and what Spring does with it.

  • We've used it
  • What does it do?
  • Let's look inside

What Spring does

When the app starts, Spring scans our package for classes. It finds the class marked at Rest Controller, and creates one object from it. It reads each mapping, and builds a table of paths. When a request arrives, Spring looks up the path, and calls the right method. Then it turns the return value into the response.

  1. Scan the package
  2. Create one controller object
  3. Build a table of paths
  4. Request → right method
  5. Return value → response

@Controller and @RestController

There are two kinds of controller. A plain at Controller usually returns the name of an HTML page to show. At Rest Controller returns data, like text or JSON, straight into the response. For APIs, we always use at Rest Controller.

@Controller

  • Returns a page nameHTML web pagesServer-side pages

@RestController

  • Returns dataText or JSONAPIs: this course

Return types

A controller method can return many types. A string is sent as plain text. An int becomes a number, and a boolean becomes true or false. Run it. Each value comes back as the body of the response.

ShopController.javajava
@RestController
public class ShopController {

    @GetMapping("/name")
    public String name() {
        return "Riverside Books";
    }

    @GetMapping("/count")
    public int count() {
        return 3;
    }

    @GetMapping("/open")
    public boolean open() {
        return true;
    }
}
Output
$ curl localhost:8080/name
Riverside Books
$ curl localhost:8080/count
3
$ curl localhost:8080/open
true
Also uses _curl.sh
curl localhost:8080/name
curl localhost:8080/count
curl localhost:8080/open

Summary

At Rest Controller marks a class whose methods answer requests with data. Spring creates the object, and routes each request to the right method. Next, at Get Mapping.

Key takeaways
  • Spring creates it
  • Routes requests
  • Returns data
Next up: @GetMapping — mapping paths