How do I map a request to a controller in Spring MVC?

In Spring MVC, you can map a request to a controller using the @RequestMapping (or aliases like @GetMapping, @PostMapping, etc.) annotation on a method. These annotations define a specific URL path and HTTP method that the method will handle. Here’s how you can do it:

Step-by-Step Instructions:

  1. Annotate the Class as a Controller: Use the @Controller annotation (or @RestController for REST APIs) on the class to indicate that it is a controller in your Spring application.
  2. Map URLs with @RequestMapping: Use the @RequestMapping annotation on methods to specify the URL patterns you want to map HTTP requests to. You can also use HTTP method-specific annotations, such as @GetMapping and @PostMapping.

Example

package org.kodejava.app;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/my-controller") // Base path for all endpoints in the controller
public class MyController {

    // Handles GET requests to /my-controller/hello
    @GetMapping("/hello")
    @ResponseBody
    public String sayHello() {
        return "Hello, World!";
    }

    // Handles POST requests to /my-controller/data
    @PostMapping("/data")
    @ResponseBody
    public String handleDataSubmission() {
        return "Data submitted successfully!";
    }
}

Key Annotations:

  1. @Controller: Marks the class as a Spring MVC controller.
  2. @RequestMapping: Used to map web requests onto specific methods or classes. It can be used with a combination of HTTP methods, URL patterns, and request parameters.
    @RequestMapping(value = "/example", method = RequestMethod.GET)
    
  3. HTTP Method-Specific Annotations: These are shorthand annotations for specific HTTP methods:
    • @GetMapping for GET requests
    • @PostMapping for POST requests
    • @PutMapping for PUT requests
    • @DeleteMapping for DELETE requests
    • @PatchMapping for PATCH requests

Notes:

  1. Class-Level @RequestMapping: If you specify a base path with @RequestMapping at the class level, all methods will inherit this as part of their path.
  2. Return Types:
    • Use @ResponseBody to return plain text, JSON, or XML directly in the HTTP response body.
    • If you are returning a view name, you don’t need @ResponseBody.
  3. Path Variables and Query Parameters: You can also handle dynamic path variables using the @PathVariable and request parameters using the @RequestParam annotations.

Example with Path Variables and Request Parameters:

package org.kodejava.app;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {

    // Dynamic path variable
    @GetMapping("/{id}")
    public String getUserById(@PathVariable("id") Long id) {
        return "User ID: " + id;
    }

    // Query parameter
    @GetMapping("/search")
    public String searchUsers(@RequestParam("name") String name) {
        return "Searching for user: " + name;
    }
}

By following this pattern, you can map requests to specific controller methods and build robust web applications with Spring MVC.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.