Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 3526

A Quick Guide to Spring MVC Matrix Variables

$
0
0

I just released the Starter Class of "Learn Spring Security":

>> CHECK OUT THE COURSE

1. Overview

The URI specification RFC 3986 defined URI path parameters as name-value pairs. Matrix variables is a Spring coined term, and an alternative implementation for passing and parsing URI path parameters.

Matrix variables support became available in Spring MVC 3.2 and is meant to simplify requests with a large number of parameters.

In this article, we will show how we can simplify complex GET requests that use either variable or optional path parameters inside the different path segments of an URI.

2. Configuration

In order to enable Spring MVC Matrix Variables, let’s start with the configuration:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }
}

Otherwise, they’re disabled by default.

3. How to Use Matrix Variables

These variables can appear in any part of the path and the character equals (“=”) is used for giving values and the semicolon(‘;’) for delimiting each matrix variable. On the same path, we can also repeat the same variable name or separate different values using the character comma(‘,’).

Our example has a controller that provides information about the employees. Each employee has a working area and we are able to do a search by that attribute. The following request could be used for searching:

http://localhost:8080/spring-mvc-java/employeeArea/workingArea=rh,informatics,admin

or like this:

http://localhost:8080/spring-mvc-java
  /employeeArea/workingArea=rh;workingArea=informatics;workingArea=admin

When we want to refer to these variables in Spring MVC, we should use the annotation @MatrixVariable.

In our examples, we will use the Employee class:

public class Employee {

    private long id;
    private String name;
    private String contactNumber;

    // standard setters and getters 
}

And also the Company class:

public class Company {

    private long id;
    private String name;

    // standard setters and getters
}

These two classes will bind the request parameters.

4. Defining Matrix Variable Properties

We are able to define required or default properties for the variable. In the following example, the contactNumber is required, so it must be included in our path, something like this:

http://localhost:8080/spring-mvc-java/employeesContacts/contactNumber=223334411

The request will be handled by the following method:

@RequestMapping(value = "/employeesContacts/{contactNumber}", 
  method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<List<Employee>> getEmployeeBycontactNumber(
  @MatrixVariable(required = true) String contactNumber) {
    List<Employee> employeesList = new ArrayList<Employee>();
    ...
    return new ResponseEntity<List<Employee>>(employeesList, HttpStatus.OK);
}

As a result, we will get all the employees which have the contact number 223334411.

5. Complement Parameter

Matrix variables can complement path variables.

For example, we are searching an employee for his/her name, but we can also include the starting numbers of his/her contact number.

The request for this search should be like this:

http://localhost:8080/spring-mvc-java/employees/John;beginContactNumber=22001

The request will be handled by the following method:

@RequestMapping(value = "/employees/{name}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<List<Employee>> getEmployeeByNameAndBeginContactNumber(
  @PathVariable String name, @MatrixVariable String beginContactNumber) {
    List<Employee> employeesList = new ArrayList<Employee>();
    ...
    return new ResponseEntity<>(employeesList, HttpStatus.OK);
}

As a result, we will get all the employees which have the contact number 22001 or whose name is John.

6. Binding All Matrix Variables

If, for some reason, we want to get all the variables that are available on the path, we can binding them to a Map:

http://localhost:8080/spring-mvc-java/employeeData/id=1;name=John;contactNumber=2200112334

This request will be handled by the following method:

@RequestMapping(value = "employeeData/{employee}",
  method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Map<String, String>> getEmployeeData(
  @MatrixVariable Map<String, String> matrixVars) {
    return new ResponseEntity<>(matrixVars, HttpStatus.OK);
}

Of course, we are able to restrict binding to the matrix variables of a specific part of the path. For example, if we have a request like this:

http://localhost:8080/spring-mvc-java/
  companyEmployee/id=2;name=Xpto/employeeData/id=1;name=John;
  contactNumber=2200112334

And we only want to get all the variables that belong to employeeData, then we should use as an input parameter this:

@RequestMapping(
 value = "/companyEmployee/{company}/employeeData/{employee}",
 method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Map<String, String>> getEmployeeDataFromCompany(
  @MatrixVariable(pathVar = "employee") Map<String, String> matrixVars) {
  ...
}

7. Partial Binding

Apart from simplicity, flexibility is another gain, matrix variables can be used in a variety of different ways. For example, we are able to get each variable from each path segment. Consider the following request:

http://localhost:8080/spring-mvc-java/
  companyData/id=2;name=Xpto/employeeData/id=1;name=John;
  contactNumber=2200112334

If we only want to know the matrix variable name of the companyData segment, then, we should use as an input parameter the following:

@MatrixVariable(value="name", pathVar="company") String name

8. Conclusion

This article illustrated some of the various ways that matrix variables can be used.

It’s very important to understand how this new tool can deal with requests that are too complex or help us add more parameters to delimit our search.

The implementation of all these examples and code snippets can be found in a github project – this is an Eclipse based project, so it should be easy to import and run as it is.

Get the early-bird price (20% Off) of my upcoming "Learn Spring Security" Course:

>> CHECK OUT THE COURSE


Viewing all articles
Browse latest Browse all 3526

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>