How do you extract URI template variables in Spring MVC?

Table of Contants

Introduction

In Spring MVC, handling URI template variables is a common requirement when building RESTful APIs or web applications. URI template variables are dynamic segments of the URL that can be extracted and used in controller methods. These variables are typically used to pass data, such as resource IDs, query parameters, or filters, to the backend.

This guide will explain how to extract URI template variables in Spring MVC using @PathVariable, @RequestParam, and regular expressions to handle different types of variable extraction from request URIs.

Methods to Extract URI Template Variables in Spring MVC

1. Using **@PathVariable** to Extract Path Variables

The most common way to extract URI template variables in Spring MVC is through the @PathVariable annotation. Path variables are extracted directly from the URI path and mapped to method parameters.

Example: Extracting Path Variables with @PathVariable

In this example:

  • The {userId} in the URL path is a template variable.
  • The @PathVariable annotation binds the value of the path variable to the userId parameter in the method.
  • If a request is made to /api/user/123, the method will return "User ID: 123".

Example Request:

Response:

2. Extracting Multiple Path Variables

You can extract multiple path variables in a single request by using multiple @PathVariable annotations.

Example: Extracting Multiple Path Variables

In this example:

  • The URL contains two path variables: {userId} and {postId}.
  • Both are extracted and mapped to their respective method parameters.
  • A request to /api/users/123/posts/456 would return "User ID: 123, Post ID: 456".

Example Request:

Response:

3. Using Regular Expressions for More Complex Path Variables

Spring MVC supports regular expressions to match more complex patterns in path variables. This allows you to restrict the values that can be extracted from the URI.

Example: Using Regular Expressions in Path Variables

In this example:

  • The @PathVariable annotation uses regular expressions to match the year, month, and day as 4-digit, 2-digit, and 2-digit values, respectively.
  • A request to /api/2023/12/15 would be matched and return "Date: 2023-12-15".

Example Request:

Response:

4. Using **@RequestParam** to Extract Query Parameters

In addition to extracting path variables, Spring MVC provides the @RequestParam annotation to extract query parameters from the URI. Query parameters are typically used for filters, sorting, or pagination in REST APIs.

Example: Extracting Query Parameters with @RequestParam

In this example:

  • The @RequestParam annotation is used to extract the query and limit query parameters from the URL.
  • If a request is made to /api/search?query=spring&limit=5, the method will return "Search query: spring, Limit: 5".
  • If no limit is provided, it defaults to 10, as specified in the method signature.

Example Request:

Response:

5. Extracting Optional Query Parameters

You can make query parameters optional by setting default values or by using Optional<T> for more flexibility.

Example: Using Optional Query Parameters

In this example:

  • The limit query parameter is optional.
  • If limit is provided, it will be used. If not, it will default to 10 using the Optional.orElse() method.

Example Request:

Response:

6. Extracting URI Variables in **@RequestMapping**

The @RequestMapping annotation allows you to handle different HTTP methods and paths. You can extract URI variables in the same way as with @GetMapping, @PostMapping, etc.

Example: Extracting URI Variables with @RequestMapping

This works similarly to @GetMapping and allows for more flexible mappings (e.g., supporting multiple HTTP methods for the same URL).

Conclusion

In Spring MVC, extracting URI template variables can be done easily using annotations like @PathVariable and @RequestParam. These annotations provide flexibility in handling:

  • Path variables using @PathVariable for extracting dynamic parts of the URL.
  • Query parameters using @RequestParam for extracting values from the query string.
  • Regular expressions for more complex variable patterns.
  • Optional query parameters for more flexible handling of URL parameters.

These methods are essential for building RESTful APIs and handling different types of requests with dynamic inputs in a clean and maintainable way.

Similar Questions