【问题标题】:Spring MVC and get query parameters with JacksonSpring MVC 并使用 Jackson 获取查询参数
【发布时间】:2019-07-25 19:01:08
【问题描述】:

我正在尝试将其他查询参数捕获到 Map<String,String> 例如:http://url.example/route?lastIndex=10&sort=-afield&othera=test&otherb=test 我希望将otheraotherb 存储在地图中。有可能吗?

class MyRequest {
   private String lastIndex;
   private String sort;
   private Map<String,String> myFilters;
}

@RestControler
class MyController {
   @GetMapping("/route")
   public String get(MyRequest request) {
     return "OK";
  }
}

【问题讨论】:

    标签: spring spring-boot spring-mvc get jackson


    【解决方案1】:

    如果你打算使用MyRequest 类,我不认为它可能会起作用。鉴于这些是 AJAX GET 请求(因为它是 @RestController),您可以使用 @RequestBody

    @RestControler
    class MyController {
       @GetMapping("/route")
       public String get(@RequestBody MyRequest request) {
         return "OK";
      }
    }
    

    并像这样以 JSON 格式发送请求,而不是使用查询参数:

    curl -X GET \
      http://url.example/route/ \
      -H 'Content-Type: application/json' \
      -d '{
      "lastIndex": "var",
      "sort": "there",
      "myFilters":{
        "hello": "there",
        "hello1": "there1"
      }'
    }
    

    GET 请求可以有正文吗?

    规格有点模棱两可 - 你可以阅读更多关于它here。但是,如果您使用 AJAX GET 请求,Spring Boot 运行时容器(我在 Spring Boot 2.0.4.RELEASE 中检查了 Tomcat、Jetty 和 UnderTow)支持它们。

    【讨论】:

    • AJAX GET 请求与正文工作,我刚刚在我的 Spring Boot 应用程序中进行了测试...因为这里使用了 RestController,它 AJAX 正确
    • 它是否有效取决于您使用的浏览器和运行时。由于规范对此有点模棱两可。另请参阅stackoverflow.com/questions/978061/http-get-with-request-body
    • 它可以在 Spring Boot 中运行,你可以试试看 :) 无论如何它都不依赖于浏览器!
    • 如前所述,取决于容器。它可能在 Tomcat 上运行,但在使用 Jetty/Netty/Undertow 时可能无法运行。
    • @M.Deinum 它在 Tomcat、Jetty 和 Undertow 中工作,这些 spring 容器支持它......
    【解决方案2】:

    由于您的 MyRequset 类仅包含字符串参数,因此明智的做法可能是使用类似

       @GetMapping("/route")
       public MyRequest get(@RequsetParam Map<String,String> allParams) 
    

    然后按照你喜欢的方式转换你的参数映射。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多