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 MVC @RequestParam Annotation

The @RequestParam annotation is used in Spring MVC to bind request parameters from the query string or form data to method parameters in a controller. By using this annotation, you can access the value of a specific request parameter.

Key Points:

  1. Basic Usage: Binds the value of a request parameter to a method parameter.

  2. Default Value: You can specify a default value for a request parameter if it's not present in the request.

  3. Required Parameter: By default, @RequestParam considers the parameter as required. If the parameter is absent in the request, an exception is thrown. However, you can set the required attribute to false if the parameter is optional.

Examples:

  1. Basic Usage: Suppose the request URL is /greet?name=John

    @GetMapping("/greet")
    public String greet(@RequestParam String name, Model model) {
        model.addAttribute("message", "Hello, " + name);
        return "greetingView";
    }
    
  2. Specify Parameter Name: If the method parameter name is different from the request parameter name, you can specify the request parameter name using value attribute:

    Request URL: /greet?username=John

    @GetMapping("/greet")
    public String greet(@RequestParam(value = "username") String name, Model model) {
        model.addAttribute("message", "Hello, " + name);
        return "greetingView";
    }
    
  3. Default Value: If the name parameter isn't present in the request, it defaults to "Guest".

    @GetMapping("/greet")
    public String greet(@RequestParam(defaultValue = "Guest") String name, Model model) {
        model.addAttribute("message", "Hello, " + name);
        return "greetingView";
    }
    

    For a request URL /greet, the message will be "Hello, Guest".

  4. Optional Parameters: To make a request parameter optional:

    @GetMapping("/greet")
    public String greet(@RequestParam(required = false) String name, Model model) {
        if (name != null) {
            model.addAttribute("message", "Hello, " + name);
        } else {
            model.addAttribute("message", "Hello, Guest");
        }
        return "greetingView";
    }
    
  5. Multiple Request Parameters: If you want to bind multiple parameters:

    Request URL: /details?id=1&name=John

    @GetMapping("/details")
    public String userDetails(@RequestParam int id, @RequestParam String name, Model model) {
        // your logic
        return "detailsView";
    }
    
  6. Map All Parameters: If you don't know beforehand what request parameters will be sent, you can use a Map:

    @GetMapping("/params")
    public String displayParams(@RequestParam Map<String, String> allParams, Model model) {
        model.addAttribute("params", allParams);
        return "paramsView";
    }
    

Notes:

  • Always validate request parameters to ensure data integrity and avoid potential security issues.

  • If the request parameter is missing and neither a default value is specified nor is the required attribute set to false, Spring will throw a MissingServletRequestParameterException.

  1. Spring MVC @RequestParam Example:

    • Description: This is a basic example illustrating the usage of @RequestParam in a Spring MVC controller method.

    • Code Snippet: (Controller)

      @Controller
      public class UserController {
      
          @GetMapping("/user")
          public String getUserById(@RequestParam("id") Long userId, Model model) {
              // Retrieve user by ID and add to the model
              return "userDetails";
          }
      }
      
  2. Working with Request Parameters in Spring MVC:

    • Description: This example showcases the process of working with multiple request parameters in a Spring MVC controller method.

    • Code Snippet: (Controller)

      @Controller
      public class ProductController {
      
          @GetMapping("/products")
          public String getProducts(@RequestParam("category") String category, @RequestParam("sortBy") String sortBy, Model model) {
              // Retrieve products based on category and sorting criteria
              return "productList";
          }
      }
      
  3. Spring MVC @RequestParam vs @PathVariable:

    • Description: This example provides a comparison between @RequestParam and @PathVariable in Spring MVC for handling request parameters.

    • Code Snippet: (Controller - showcasing both annotations)

      @Controller
      public class OrderController {
      
          @GetMapping("/order")
          public String getOrderById(@RequestParam("orderId") Long orderId, @PathVariable("customerId") Long customerId, Model model) {
              // Retrieve order details based on orderId and customerId
              return "orderDetails";
          }
      }
      
  4. Using @RequestParam with Default Values in Spring MVC:

    • Description: This example demonstrates how to use @RequestParam with default values in a Spring MVC controller method.

    • Code Snippet: (Controller)

      @Controller
      public class SearchController {
      
          @GetMapping("/search")
          public String searchProducts(@RequestParam(name = "query", defaultValue = "Spring Framework") String searchQuery, Model model) {
              // Perform product search based on the query
              return "searchResults";
          }
      }
      
  5. Optional @RequestParam in Spring MVC:

    • Description: This example illustrates the use of Optional with @RequestParam in a Spring MVC controller for handling optional parameters.

    • Code Snippet: (Controller)

      @Controller
      public class UserController {
      
          @GetMapping("/user")
          public String getUserById(@RequestParam("id") Optional<Long> userId, Model model) {
              // Retrieve user by ID if present
              return "userDetails";
          }
      }