STAGE 4 OF 37

Stage 4: read numbers from the URL path

Learning path / Stage 4 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.

Keep the query-parameter example and add a second method. This time the numbers appear as path sections.

Download spring-path-variables.zip

Follow the request
GET /add/10/20 -> addUsingPath(10, 20) -> return 30 -> browser displays 30

In /add/{a}/{b}, the braces mark values captured from the path. @PathVariable("a") supplies the captured value to first. @PathVariable("b") supplies second. Java performs the addition. Both methods can exist together because /add and /add/{a}/{b} are different mappings.

Try and verify: Open /add/10/20 and expect 30. Open /add/7/5 and expect 12. Compare with /add?a=7&b=5: the input location changes, but the arithmetic is the same.

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.PathVariable;
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;
    }
    @GetMapping("/add/{a}/{b}")
    @ResponseBody
    public int addUsingPath(@PathVariable("a") int first,
                            @PathVariable("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 4: the Spring words to recognize

Focus: Use an existing controller with a different location for its input values.

TermOur concrete exampleIts place in Spring
@PathVariable/add/10/20 supplies 10 and 20 through {a} and {b}.Spring MVC binds captured URL path values to method arguments.
Request mapping — reused/add and /add/{a}/{b} select different methods.Spring MVC chooses a handler using the configured path and HTTP method.

You should now be able to say: The arithmetic is unchanged; @PathVariable reads numbers from the URL path.

One small check: In /add/7/5, which value goes into first and which goes into second?

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