【问题标题】:What are the advantages of @MatrixVariable over @RequestParam?@MatrixVariable 相对于@RequestParam 的优势是什么?
【发布时间】:2019-02-01 09:28:02
【问题描述】:

我在这篇文章中读到http://www.kscodes.com/spring-mvc/spring-mvc-matrix-variable-example/,其中一个优点是您可以将变量类型Map 用于矩阵变量,而在使用@RequestParam 时不能使用此类型。但除此之外,我为什么应该使用@MatrixVariable 而不是@RequestParam,还有其他原因吗?

谢谢

【问题讨论】:

    标签: java spring spring-mvc spring-boot spring-data


    【解决方案1】:

    @RequestParam 不同,@MatrixVariable 由分号 ; 分隔,多个值由逗号 , 分隔。阅读其文档:

    指示方法参数应绑定到路径段内的名称-值对的注释。支持 RequestMapping 带注释的处理程序方法。

    有很多用法示例和变体。以下是一些例子:

    • 网址:localhost:8080/person/Tom;age=25;height=175 和控制器:

      @GetMapping("/person/{name}")
      @ResponseBody
      public String person(
          @PathVariable("name") String name, 
          @MatrixVariable("age") int age,
          @MatrixVariable("height") int height) {
      
          // ...
      }
      
    • 它甚至可以映射到String[]

      网址:localhost:8080/person/Tom;languages=JAVA,JAVASCRIPT,CPP,C 和控制器

      public String person(
          @PathVariable("name") String name, 
          @MatrixVariable("languages") String[] languages) {
      
          // ...
      }
      

    【讨论】:

    • 好的,所以另一个优点是您可以将数组作为矩阵变量值发送?这是@RequestParam 的唯一优势,还是还有其他优势?感谢您的回答。
    • 如果你不介意的话。你能给我一个用法的例子吗?与使用 @RequestParam 相比,它清楚地显示了它的好处
    • @Maurice:我已经包含了两个示例,更多可以在 Google 上找到(我建议您在 @MatrixVariable usages example 键下找到 ProgramCreek。此注释可以轻松映射多个或可变的数字值分隔与,;
    猜你喜欢
    • 2011-06-17
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多