STAGE 3 OF 37

Stage 3: read two query parameters and return their sum

Learning path / Stage 3 of 37

Before you start: use JDK 21+ and Maven 3.9+. Extract this stage’s project and open a terminal in its pom.xml folder. Complete the setup below, including a database connection where required, then run 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

Follow the request
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
src/main/java/com/edupoly/hello/CalculatorController.java — complete file
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.

TermOur concrete exampleIts place in Spring
@RequestParama=10 and b=20 become the method arguments first and second.Spring MVC binds named request parameters to Java method arguments.
Type conversionThe URL text "10" becomes a Java int value.Spring MVC converts request text to the declared argument type.
@ResponseBodyThe 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.

Java 21 · Spring Boot 4.1.1 · Edupoly