0
0
Spring Bootframework~5 mins

@RequestMapping for base paths in Spring Boot

Choose your learning style9 modes available
Introduction

@RequestMapping for base paths helps organize your web app by grouping related URLs under one main path. It makes your code cleaner and easier to manage.

You want all URLs in a controller to start with the same base path, like '/users' for user-related actions.
You want to avoid repeating the same path prefix on every method in a controller.
You want to clearly separate different parts of your app by URL structure.
You want to handle all requests under a common path in one place.
Syntax
Spring Boot
@RestController
@RequestMapping("/basepath")
public class YourController {
    @RequestMapping("/subpath")
    public String method() {
        // handle request
        return "response";
    }
}

The base path is set on the class level.

Method-level @RequestMapping paths are appended to the base path.

Examples
All URLs start with '/api'. The method handles '/api/status'.
Spring Boot
@RestController
@RequestMapping("/api")
public class ApiController {
    @RequestMapping("/status")
    public String status() {
        return "OK";
    }
}
Both methods share the base path '/products'. URLs are '/products/list' and '/products/detail'.
Spring Boot
@RestController
@RequestMapping("/products")
public class ProductController {
    @RequestMapping("/list")
    public String list() {
        return "Product list";
    }

    @RequestMapping("/detail")
    public String detail() {
        return "Product detail";
    }
}
Sample Program

This controller handles requests starting with '/greetings'. The two methods respond to '/greetings/hello' and '/greetings/bye'.

Spring Boot
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/greetings")
public class GreetingController {

    @RequestMapping("/hello")
    public String sayHello() {
        return "Hello!";
    }

    @RequestMapping("/bye")
    public String sayBye() {
        return "Goodbye!";
    }
}
OutputSuccess
Important Notes

Use @RestController to combine @Controller and @ResponseBody for simple REST APIs.

Base path helps avoid repeating common URL parts on every method.

Paths are case sensitive by default.

Summary

@RequestMapping at class level sets a base path for all methods inside.

Method-level @RequestMapping paths add to the base path.

This keeps URL structure organized and code cleaner.