Spring Boot @RequestMapping Example

1. Introduction

The @RequestMapping annotation in Spring Boot provides a powerful way to handle routing for web applications, enabling flexible mapping of URLs to controllers and handler methods.

Key Points:

1. @RequestMapping can handle multiple HTTP methods like GET, POST, PUT, and DELETE.

2. It supports various parameters for headers, URL patterns, and media types.

3. This annotation can be applied to both controller classes and methods.

2. Implementation Steps

1. Set up a Spring Boot project with web dependencies.

2. Create a controller with a class-level @RequestMapping to define a base URI.

3. Add method-level @RequestMapping annotations for handling different endpoints and methods.

4. Use additional attributes of @RequestMapping for headers and parameters.

5. Test the controller's endpoints to ensure that the mappings are correct.

3. Implementation Example

Here is the complete code that demonstrates the usage of @RequestMapping annotation:
// Step 2: Define the controller with a base URI
@Controller
@RequestMapping("/api")
public class ExampleController {

    // Step 3: Add a method to handle GET requests
    @RequestMapping(value = "/items", method = RequestMethod.GET)
    public ResponseEntity<List<String>> getItems() {
        // Simulate item retrieval logic
        List<String> items = Arrays.asList("Item1", "Item2");
        return new ResponseEntity<>(items, HttpStatus.OK);
    }

    // Step 3: Add a method to handle POST requests
    @RequestMapping(value = "/items", method = RequestMethod.POST)
    public ResponseEntity<String> addItem(@RequestBody String item) {
        // Simulate item creation logic
        return new ResponseEntity<>("Item added: " + item, HttpStatus.CREATED);
    }

    // Step 4: Handle DELETE requests with a custom header
    @RequestMapping(value = "/items/{id}", method = RequestMethod.DELETE, headers = "action=delete")
    public ResponseEntity<String> deleteItem(@PathVariable("id") String itemId) {
        // Simulate delete logic
        return new ResponseEntity<>("Item deleted: " + itemId, HttpStatus.OK);
    }
}

// Step 5: Main application class to bootstrap the application
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Output:

// For GET /api/items:
["Item1", "Item2"]
// For POST /api/items with body "NewItem":
Item added: NewItem
// For DELETE /api/items/123 with header "action=delete":
Item deleted: 123

Explanation:

1. @Controller designates the ExampleController as a controller in the Spring application context.

2. @RequestMapping("/api") at the class level sets the base path for all methods within ExampleController.

3. @RequestMapping on getItems defines a GET endpoint /api/items that returns a list of items.

4. @RequestMapping on addItem defines a POST endpoint /api/items that accept an item as a request body and adds it.

5. @RequestMapping with custom headers in deleteItem sets up a DELETE endpoint that deletes an item by its ID, but only if the header "action=delete" is present.

6. The Application class is the entry point for the Spring Boot application, enabling the setup and testing of the defined @RequestMapping endpoints.


Comments