Spring MVC: Reading URI Path Variables

This tutorial will teach you how to retrieve URI path variables in your Spring MVC web application.

Spring Web MVC | 08 | Read URI Path...

Define Path Variable

To define a path variable in the URI path, we use curly brackets. For example, the @GetMapping annotation below specifies one path variable called userId, which is surrounded by curly brackets.

@GetMapping(path="/users/{userId}")

@PathVariable Annotation

To read a URI path variable, we use the @PathVariable annotation. The code example below uses the @PathVariable annotation to read the URI path parameter called “userId” and bind it to a method argument.

It’s important to note that the name in the @PathVariable annotation must match the name of the path parameter “userId” in the @GetMapping annotation.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class UsersController {

    @GetMapping(path="/users/{userId}")
    public ModelAndView getAlbum(@PathVariable("userId") String userId) {

        ModelAndView modelAndView = new ModelAndView("album");
        modelAndView.addObject("userId", userId);

        return modelAndView;
    }
}

Reading Multiple Path Variables

To read multiple path variables, we first define all path variables in the request mapping annotation. For example, the following request mapping annotation with @GetMapping defines two path variables:

  • {userId}
  • {albumId}
@GetMapping(path="/users/{userId}/albums/{albumId}")

In this case, the variables {userId} and {albumId} can be accessed and used in the controller method using the @PathVariable annotation.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class UsersController {

    @GetMapping(path="/users/{userId}/albums/{albumId}")
    public ModelAndView getAlbum(@PathVariable("userId") String userId,
                                @PathVariable("albumId") String albumId) {
        ModelAndView modelAndView = new ModelAndView("album");
        modelAndView.addObject("userId", userId);
        modelAndView.addObject("albumId", albumId);
        return modelAndView;
    }
}

This is a Java class for a Spring MVC controller that handles GET requests for a path that contains two path variables: userId and albumId. The @GetMapping annotation specifies the path pattern for this request, and the @PathVariable annotations on the method parameters instruct Spring to bind the values of the userId and albumId path variables to the respective method parameters. The method returns a ModelAndView object with a view name of “album” and adds the userId and albumId values as attributes to the model.

Reading Path Variables into Map

You can also read all URI path variables and make them available to your method as key-value pairs in a Map. If the method argument is Map<String, String>, then the map is populated with all path variable names and values.

Notice how the method signature changes in the code examples below. Instead of reading each path variable separately, we use a Map as a method argument.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Controller
public class UsersController {

    @GetMapping(path="/users/{userId}/albums/{albumId}")
    public ModelAndView getAlbum(@PathVariable Map<String, String> pathVariables) {

        ModelAndView modelAndView = new ModelAndView("album");
        modelAndView.addObject("userId", pathVariables.get("userId"));
        modelAndView.addObject("albumId", pathVariables.get("albumId"));

        return modelAndView;
    }
}

What if a path variable is not present in the URL path?

If a path variable is not present in the URL path, Spring Boot will throw a MissingPathVariableException. This exception indicates that the expected path variable is missing from the URL path, and it will be thrown by Spring Boot’s request mapping infrastructure.

You can handle this exception by adding an @ExceptionHandler method in your controller class, which will allow you to provide a custom response or error message to the client. Alternatively, you can also use the required attribute of the @PathVariable annotation to specify whether the path variable is required or not. If required is set to true (the default), Spring Boot will throw an exception if the path variable is missing. If required is set to false, Spring Boot will assign null to the corresponding method parameter if the path variable is missing.

Frequently asked questions

  • Is it possible to have optional path variables?
    Yes, it is possible to have optional path variables. To make a path variable optional, you can enclose it in square brackets in the @GetMapping annotation. For example, if you have a path variable called “optionalParam”, you can make it optional using the following @GetMapping annotation: @GetMapping(“/path/{requiredParam}[/{optionalParam}]”).
  • Can I use regular expressions in the path variables?
    Yes, it is possible to use regular expressions in the path variables. You can use the @Pattern annotation to validate path variables using regular expressions.
  • Can I use path variables in the request body instead of the URL path?
    No, path variables are part of the URL path and cannot be used in the request body.
  • What are some best practices for using path variables in Spring MVC?
    Some best practices for using path variables in Spring MVC include using descriptive and meaningful names for path variables, validating path variables using annotations, and handling errors related to path variables using exception handling. It is also recommended to avoid using too many path variables in a single URL path, as this can make the URL difficult to read and understand.

I hope this tutorial was helpful for you. To learn more about building web applications with the Spring Framework, please visit the Spring Web MVC category. You will find many useful tutorials there.

Happy learning!

Leave a Reply

Your email address will not be published. Required fields are marked *