Spring MVC Matrix Variable Example

The URL can have name-value pairs within its path segment. To map these pairs correctly Matrix Variables can be used in Spring MVC. Lets see some of the Spring MVC Matrix Variable Examples and how we can configure these variables in our app.

1. Configuration

For using the Matrix Variables you need to enable it first. You can do that in 2 ways
a. Set the removeSemicolonContent property of RequestMappingHandlerMapping to false. By default it is set to true.

b. In the MVC namespace, the element has an enable-matrix-variables attribute that should be set to true. By default it is set to false.

2. Simple Matrix Variable using @MatrixVariable

Matrix Variables are separated with ; semicolon.
e.g. /andriod;name=marshmallow;version=6.0.2

Multiple variables can be separated with , commaor repeating the variable name.

These variables can be mapped to a method param using @MatrixVariable

3. Matrix Variable Sequence

Matrix variables can be present in any part of the URL, so to determine which matrix variable maps to which element we use value and pathVar attributes


4. Matrix Variable Optional and Default value attributes

Matrix can be optional by setting the required attribute to false. We can also provide default values to them using the defaultValue attribute

5. Map of Matrix Variable

Unlike the other variables , Matrix variables can also be obtained in a map.

Hope you liked the Spring MVC Matrix Variable Examples.