Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the advantages of @MatrixVariable over @RequestParam?

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

like image 928
Maurice Avatar asked Oct 25 '25 13:10

Maurice


1 Answers

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) {
    
        // ...
    }
    
like image 168
Nikolas Charalambidis Avatar answered Oct 28 '25 03:10

Nikolas Charalambidis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!