🎓 A1Learner
🔍
0 of 50 lessons completed

Many Routes in One Controller

Many routes in one controller means one class answers several addresses. Each method in the class ties itself to its own address.

One more route

This method answers /welcome with its own text.

@GetMapping("/welcome")
public String welcome() {
    return "Welcome to Spring Boot!";
}

Ask for /welcome

This command asks the app for the answer at /welcome.

curl http://localhost:8080/welcome

Example

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RoutesController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello, Spring Boot!";
    }

    @GetMapping("/welcome")
    public String welcome() {
        return "Welcome to Spring Boot!";
    }

    @GetMapping("/goodbye")
    public String goodbye() {
        return "Goodbye!";
    }
}

Key points

  • One controller can hold many methods.
  • Each method ties itself to its own address.
  • Each address must differ from the others.
  • The methods share the class and its annotation.
  • A request reaches only the method for its address.
  • New routes need only a new method in the class.

In this example, the annotation marks RoutesController as a controller. The first method answers /hello with the text Hello, Spring Boot! The second method answers /welcome with the text Welcome to Spring Boot! The third method answers /goodbye with the text Goodbye! A request to /hello gets the text Hello, Spring Boot!

Note

The class stays one controller, even with many routes.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How do you add a route to a controller?