Stage 3: read two query parameters and return their sum
Learning path / Stage 3 of 37
mvn spring-boot:run. Use the port specified for this stage and stop with Ctrl+C.Move from serving a file to calculating an answer in Java. The browser sends two numbers after the question mark in the URL.
Download spring-request-params.zip
GET /add?a=10&b=20 -> add(10, 20) -> return 30 -> browser displays 30@RequestParam("a") reads the query parameter named a and converts it to int. The Java variable first receives that number. The same happens for b and second. @ResponseBody sends the returned number directly as response data. No HTML result page or template engine is used in this stage.
Try and verify: Open /add?a=10&b=20 and expect 30. Try /add?a=7&b=5 and expect 12. A missing or nonnumeric required value produces HTTP 400.
Open the files to study in this stage
package com.edupoly.hello;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class CalculatorController {
@GetMapping("/add")
@ResponseBody
public int add(@RequestParam("a") int first,
@RequestParam("b") int second) {
return first + second;
}
}
The ZIP contains every setup file and a README.html with instructions. You can run the supplied project directly.
After Stage 3: the Spring words to recognize
Focus: Read numbers from a request and send an answer directly.
| Term | Our concrete example | Its place in Spring |
|---|---|---|
| @RequestParam | a=10 and b=20 become the method arguments first and second. | Spring MVC binds named request parameters to Java method arguments. |
| Type conversion | The URL text "10" becomes a Java int value. | Spring MVC converts request text to the declared argument type. |
| @ResponseBody | The returned sum is sent directly to the browser. | Spring MVC writes the method result into the HTTP response body. |
You should now be able to say: Spring reads the query parameters, calls my Java method and sends its returned answer.
One small check: What changes if a is text such as abc instead of an integer?
Concepts used in this stage
Use the right column for a quick reminder, or open a concept above for its full explanation.