Line At A Time
Lesson 7: Taking Orders: POST
Taking Orders: POST Receive data from the caller instead of only sending it.
1import java.util.ArrayList;
2import java.util.List;
3import org.springframework.web.bind.annotation.*;
4
5@RestController
6public class OrderController {
7 private final List<String> orders = new ArrayList<>();
8
9 @PostMapping("/orders")
10 public String order(@RequestBody String pizza) {
11 orders.add(pizza);
12 return "Order received: " + pizza;
13 }
14}
Terminal
$ ./mvnw spring-boot:run
:: Spring Boot :: (v3.3.0)
Tomcat started on port 8080 (http)
Started DemoApplication in 1.24 seconds
$ curl -X POST localhost:8080/orders -d "Pepperoni"
Order received: Pepperoni
$ curl -X POST localhost:8080/orders -d "Margherita"
Order received: Margherita
Every line, explained
import java.util.ArrayList;
ArrayList: a list that can grow, for remembering the orders.
import java.util.List;
The standard-library List import again.
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 OrderController {
A controller is a perfectly ordinary Java class; the annotations are what make it special.
private final List<String> orders = new ArrayList<>();
A field on the controller, like the fields from Your First Class, with two new keywords: private means only this class can touch the list, and final means the field will always hold this same list. Spring creates ONE OrderController and reuses it for every request, so this list survives between requests: each order is added to the same list. (It lives in memory, so restarting the server empties it; real apps use a database for keeps.)
@PostMapping("/orders")
A new annotation for a new direction! GET asks a server for data; POST sends data TO the server. Creating, ordering and signing up are all POSTs. Same address style, different verb.
public String order(@RequestBody String pizza) {
@RequestBody hands you the body of the request: the data the caller sent along. Here it arrives as a String named pizza.
orders.add(pizza);
The server remembers the order by adding it to the list. This is the first lesson where a request CHANGES something on the server.
return "Order received: " + pizza;
And a confirmation goes back, so the caller knows it worked.
}
This } closes the method.
}
This } closes the class.