【问题标题】:@RequestParam and @PathVariable encapsulation@RequestParam 和 @PathVariable 封装
【发布时间】:2018-01-09 14:57:11
【问题描述】:

有没有办法将这两个值封装到一个对象中?

public ResponseEntity<TestResponse> test(@PathVariable("customerId") String customerId,
        @RequestParam(name = "reason", required = true) String reason,
        @RequestParam(name = "attribute", required = true) List<String> attributes) {

我认为我应该可以这样做:

public ResponseEntity<TestResponse> test(@MaybeSomeMagicAnnotation? Request request) {

Request 类具有这三个属性(customerId、reason、attributes)。

我使用的是 spring boot 1.5.9

【问题讨论】:

  • 你不需要任何东西。只需创建具有这三个字段的 Request 类并将其用作方法参数。

标签: java spring spring-mvc spring-boot request-mapping


【解决方案1】:

你应该可以通过定义一个匹配请求参数等的对象来做到这一点。

示例(未经测试):

public class MyRequest {
   @NotNull
   private String customerId;

   @NotNull
   private String reason;

   @NotNull
   @NotEmpty
   private List<String> attributes;

   // getters and setters left out for brevity.
}

然后在你的控制器中:

public ResponseEntity<TestResponse> test(@Valid MyRequest request) {
    ...
}

【讨论】:

  • 属性上所需的参数 Andrzej 自定义名称怎么样(集合 od 属性给出属性)?
  • @pustypawel 添加了注释来展示如何做到这一点。
  • 那个案子对我来说很清楚。属性名称是什么(在 URL 上,我想在类集合“属性”中拥有“属性”
  • 另一个问题 - 有没有办法让这个对象不可变?(当我尝试这样做时,我得到 java.lang.NoSuchMethodException: packages.Request.()
  • 好的。我检查了 spring 源代码 - 没有简单的方法可以做到这一点。我被选为第一个解决方案,我只是在控制器中手动创建我的复杂对象。谢谢
猜你喜欢
  • 2014-08-16
  • 2012-11-22
  • 2015-08-28
  • 2015-08-18
  • 1970-01-01
  • 2021-07-05
  • 2018-05-05
相关资源
最近更新 更多