0
0
Spring Bootframework~5 mins

Request mapping by method and path in Spring Boot

Choose your learning style9 modes available
Introduction

Request mapping connects web addresses and HTTP methods to specific code that runs when someone visits those addresses.

You want to run different code when someone visits different web pages.
You need to handle GET requests to show data and POST requests to save data.
You want to organize your web app so each URL does a clear job.
You want to make a REST API where each URL and method means something specific.
Syntax
Spring Boot
@RequestMapping(path = "/example", method = RequestMethod.GET)
public String exampleMethod() {
    // code here
}
Use @RequestMapping on methods or classes to link URLs and HTTP methods.
You can specify the path and the HTTP method like GET, POST, PUT, DELETE.
Examples
This runs when someone visits '/hello' with a GET request.
Spring Boot
@RequestMapping(path = "/hello", method = RequestMethod.GET)
public String sayHello() {
    return "Hello!";
}
This runs when someone sends a POST request to '/submit'.
Spring Boot
@RequestMapping(path = "/submit", method = RequestMethod.POST)
public String submitData() {
    return "Data submitted!";
}
This runs for both GET and POST requests to '/items'.
Spring Boot
@RequestMapping(path = "/items", method = {RequestMethod.GET, RequestMethod.POST})
public String handleItems() {
    return "Items handled!";
}
Sample Program

This controller has two methods for the same path '/greet'. One runs on GET requests and says hello. The other runs on POST requests and thanks the user.

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

@RestController
public class MyController {

    @RequestMapping(path = "/greet", method = RequestMethod.GET)
    public String greet() {
        return "Hello, visitor!";
    }

    @RequestMapping(path = "/greet", method = RequestMethod.POST)
    public String greetPost() {
        return "Thanks for posting!";
    }
}
OutputSuccess
Important Notes

Spring Boot also offers shortcuts like @GetMapping and @PostMapping for simpler code.

Always match the HTTP method to what your code should do (GET for reading, POST for creating, etc.).

Summary

Request mapping links URLs and HTTP methods to code.

You can specify path and method with @RequestMapping.

This helps organize web app behavior clearly.