🎓 A1Learner
🔍
0 of 50 lessons completed

Your First REST Controller

A REST controller is a Java class that answers web requests. Each method in the class answers one address.

Mark the class

This annotation marks the class as a controller.

@RestController
public class HelloController {

Return the text

This method returns the text for its address.

public String hello() {
    return "Hello, Spring Boot!";
}

Example

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello, Spring Boot!";
    }
}

Key points

  • A REST controller is a Java class that answers web requests.
  • The annotation @RestController marks the class as a controller.
  • The annotation sits above the class line.
  • Each method in the class can answer one address.
  • The method returns the text for its address.
  • Spring finds the controller when the app starts.

In this example, the annotation marks HelloController as a controller. The line above the method ties it to the address /hello. The method returns the text. A request to /hello gets the text Hello, Spring Boot!

Note

A class without the annotation is not a controller.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What marks a class as a REST controller?