4

I am reading in this article http://www.kscodes.com/spring-mvc/spring-mvc-matrix-variable-example/ that one advantage is that you can use the variable type Map for the matrix variable and you can't use this type when using @RequestParam. But aside from that, are there any other reasons for why I should use @MatrixVariable instead of @RequestParam?

Thank you

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
Maurice
  • 6,698
  • 9
  • 47
  • 104

1 Answers1

3

Unlike the @RequestParam the @MatrixVariable is separated by a semicolon ; and multiple values are separated by a comma ,. Read its documentation:

Annotation which indicates that a method parameter should be bound to a name-value pair within a path segment. Supported for RequestMapping annotated handler methods.

There are plenty of examples and variations of the usage. Here are some exapmles:

  • URL: localhost:8080/person/Tom;age=25;height=175 and Controller:

    @GetMapping("/person/{name}")
    @ResponseBody
    public String person(
        @PathVariable("name") String name, 
        @MatrixVariable("age") int age,
        @MatrixVariable("height") int height) {
    
        // ...
    }
    
  • It can be even mapped to String[].

    URL: localhost:8080/person/Tom;languages=JAVA,JAVASCRIPT,CPP,C and Controller

    public String person(
        @PathVariable("name") String name, 
        @MatrixVariable("languages") String[] languages) {
    
        // ...
    }
    
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
  • ok so another advantage is that you can send an array as a matrixvariable value? Is that the sole advantage over @RequestParam, or are there others as well? Thanks for the answer. – Maurice Aug 26 '18 at 18:42
  • also, if you don't mind. Could you give me an example of the usage? One that clearly shows its benefit as opposed to using @RequestParam – Maurice Aug 26 '18 at 18:44
  • @Maurice: I have included two examples, more can be found on Google (I suggest you [ProgramCreek](https://www.programcreek.com/java-api-examples/index.php?api=org.springframework.web.bind.annotation.MatrixVariable) under the key `@MatrixVariable usages example`. This annotation makes an easy mapping of multiple or variable number values separated with `,` and `;`. – Nikolas Charalambidis Aug 26 '18 at 18:48