Spring MVC Tutorial

Core Spring MVC

Spring MVC - Annotation

Spring MVC - Form Handling

Spring MVC with JSTL

Spring MVC with REST API

Spring MVC with Database

Spring @RequestMapping Annotation with Example

The @RequestMapping annotation is one of the most common annotations in Spring Web applications. It provides routing information and tells the Spring framework that a specific method or class should handle a particular web request.

Let's delve deeper into this annotation:

Basic Usage:

  1. At the class level: @RequestMapping can be used to define a common base URL for all methods inside a @Controller class.
  2. At the method level: It denotes a method to handle a specific URL or URL pattern.

Attributes:

  1. value: Specifies URI to be mapped. Can be absolute or relative to class-level mapping.
  2. method: Specifies HTTP methods (GET, POST, PUT, DELETE, etc.) that the method should handle.
  3. consumes: Specifies media types the method can consume from client (e.g., application/json).
  4. produces: Specifies media types the method can produce for the client.

Example:

1. Class-Level Mapping:

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

    // ... methods to handle user requests ...

}

Here, every method inside UserController will have /api/users as a prefix in its route.

2. Method-Level Mapping:

Handling a GET request:

@RequestMapping(value = "/{userId}", method = RequestMethod.GET)
public User getUserById(@PathVariable String userId) {
    // ... return user with the given ID ...
}

You can also use shortcut annotations like @GetMapping, @PostMapping, etc., which are more concise:

@GetMapping("/{userId}")
public User getUserById(@PathVariable String userId) {
    // ... return user with the given ID ...
}

Handling a POST request with a JSON body:

@PostMapping(consumes = "application/json", produces = "application/json")
public User createUser(@RequestBody User user) {
    // ... save and return the user ...
}

3. Multiple URI Patterns:

@RequestMapping(value = {"/", "/home", "/index"})
public String home() {
    // ... return home view ...
}

Running the Example:

To run the example, set up a basic Spring Boot application and add Spring Web as a dependency. Then create the UserController with the above methods.

When you run the application:

  1. Visiting /api/users/{userId} will trigger the getUserById method and return the user with the specified ID.
  2. Sending a POST request to /api/users with a JSON body representing a user will trigger the createUser method, which will save and return the user.

This gives a brief overview of the @RequestMapping annotation. It's essential for web development with Spring, and there are many other attributes and features to explore as your needs evolve.

  1. Using @RequestMapping in Spring MVC:

    • Description: @RequestMapping is a versatile annotation in Spring MVC used to map HTTP requests to handler methods in controllers.

    • Code Snippet: (Controller Method)

      @Controller
      public class MyController {
      
          @RequestMapping("/hello")
          public String hello() {
              return "hello";
          }
      }
      
  2. RequestMapping Annotation with Method Parameters in Spring:

    • Description: This example showcases how to use method parameters with @RequestMapping to capture values from the request.

    • Code Snippet: (Controller Method)

      @RequestMapping("/greet")
      public String greet(@RequestParam(name = "name") String name) {
          return "Greetings, " + name + "!";
      }
      
  3. Spring MVC RequestMapping Path Patterns:

    • Description: Demonstrates the usage of path patterns with @RequestMapping to handle multiple URL variations.

    • Code Snippet: (Controller Method)

      @RequestMapping("/products/{category}/{id}")
      public String getProductDetails(@PathVariable String category, @PathVariable int id) {
          // Process product details
          return "productDetails";
      }
      
  4. RequestMapping with Multiple URL Patterns in Spring:

    • Description: Illustrates how to specify multiple URL patterns for a single controller method using @RequestMapping.

    • Code Snippet: (Controller Method)

      @RequestMapping(value = {"/path1", "/path2"})
      public String handleMultiplePaths() {
          // Handle multiple paths
          return "multiplePaths";
      }
      
  5. RequestMapping Method Types in Spring MVC:

    • Description: Shows how to use @RequestMapping with different HTTP methods (GET, POST, etc.) for a controller method.

    • Code Snippet: (Controller Method)

      @RequestMapping(value = "/submitForm", method = RequestMethod.POST)
      public String submitForm() {
          // Handle form submission
          return "formSubmitted";
      }
      
  6. PathVariable with @RequestMapping in Spring:

    • Description: Highlights the use of @PathVariable with @RequestMapping to extract values from the URI.

    • Code Snippet: (Controller Method)

      @RequestMapping("/user/{userId}")
      public String getUserDetails(@PathVariable String userId) {
          // Fetch and display user details
          return "userDetails";
      }
      
  7. RequestMapping and HTTP Methods in Spring MVC:

    • Description: Demonstrates how to use @RequestMapping with specific HTTP methods for a more precise mapping.

    • Code Snippet: (Controller Method)

      @RequestMapping(value = "/deleteUser", method = RequestMethod.DELETE)
      public String deleteUser() {
          // Delete user logic
          return "userDeleted";
      }
      
  8. RequestMapping vs GetMapping in Spring:

    • Description: Compares the usage of @RequestMapping and @GetMapping annotations in Spring MVC.

    • Code Snippet: (Controller Method with @GetMapping)

      @Controller
      public class MyController {
      
          @GetMapping("/hello")
          public String hello() {
              return "hello";
          }
      }
      
  9. RequestMapping in Spring Boot Example:

    • Description: Shows how to use @RequestMapping in a Spring Boot application.

    • Code Snippet: (Controller Method)

      @RestController
      public class MyController {
      
          @RequestMapping("/hello")
          public String hello() {
              return "Hello from Spring Boot!";
          }
      }