Line At A Time
Lesson 2: Hello, Endpoint
Hello, Endpoint Answer your first web request.
1import org.springframework.web.bind.annotation.*;
2
3@RestController
4public class HelloController {
5 @GetMapping("/hello")
6 public String hello() {
7 return "Hello, world!";
8 }
9}
Terminal
$ ./mvnw spring-boot:run
:: Spring Boot :: (v3.3.0)
Tomcat started on port 8080 (http)
Started DemoApplication in 1.24 seconds
$ curl localhost:8080/hello
Hello, world!
Every line, explained
import org.springframework.web.bind.annotation.*;
This import brings in Spring's web annotations (@RestController, @GetMapping and friends). The .* means "everything in this package", which saves one import line per annotation.
@RestController
@RestController is an annotation: a label that starts with @ and gives Spring information about your class. This one says "this class answers web requests, and whatever its methods return should be sent back to the caller". You never call this class yourself; Spring creates it and calls it for you.
public class HelloController {
A controller is a perfectly ordinary Java class; the annotations are what make it special. By convention, classes that answer requests are called controllers, and their names end in Controller. (The DemoApplication class from lesson 1 still exists in its own file; it starts the server, and Spring finds this class automatically.)
@GetMapping("/hello")
@GetMapping maps a web address to a method. When a GET request (the normal kind a browser makes) arrives for /hello, Spring calls the method underneath. The address is called an endpoint.
public String hello() {
An ordinary method that returns a String. You never call it yourself; Spring calls it whenever a request for /hello arrives.
return "Hello, world!";
Whatever you return is the response: Spring sends this text back over the network to whoever asked. Watch the terminal after the server starts: curl is a little command-line program that makes web requests, like a browser without the window. It is the quickest way to poke at a server you are building.
}
This } closes the method.
}
This } closes the class.