Coding for All
Lesson 4: Query Parameters
Query Parameters Read values after the ? in a web address.
1import org.springframework.web.bind.annotation.*;
2
3@RestController
4public class MathController {
5 @GetMapping("/add")
6 public int add(@RequestParam int a, @RequestParam int b) {
7 return a + b;
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/add?a=2&b=3"
5
$ curl "localhost:8080/add?a=10&b=32"
42
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 MathController {
A controller is a perfectly ordinary Java class; the annotations are what make it special.
@GetMapping("/add")
A plain endpoint this time; the interesting part comes after the ? in the address.
public int add(@RequestParam int a, @RequestParam int b) {
The part of an address after a ? holds query parameters: /add?a=2&b=3 carries a=2 and b=3, chained with &. @RequestParam picks each one out by name and even converts it from text to an int for you. If a required parameter is missing, Spring answers with an error before your method even runs.
return a + b;
Your method returns an int, and Spring turns it into text for the response. To the caller, your server is now a tiny calculator.
}
This } closes the method.
}
This } closes the class.