java - @RequestParam 和@PathVariable 封装

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

有什么办法可以将这两个值封装到一个对象中吗?

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

最佳答案

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

示例(未经测试):

public class MyRequest {
   @NotNull
   private String customerId;

   @NotNull
   private String reason;

   @NotNull
   @NotEmpty
   private List<String> attributes;

   // getters and setters left out for brevity.
}

然后在你的 Controller 中:

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

关于java - @RequestParam 和@PathVariable 封装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48170915/

相关文章:

java - 如何使用带动态参数的 spring DI 构造函数

java - 无法配置 Spring MVC 应用程序

java - 使用 SAXParser 检查多个标签

java - 是否应该重用 ModelMapper 实例以利用缓存的 TypeMap?

java - 如何在加载时隐藏 RichFaces 组件?

java - 获取http响应代码和所有可用的正文

java - 如何在 Spring Boot 的构造函数中读取 application.properties 值?

spring - <context :component-scan. ../> 和 <context :property-placeholder. ../> 在分层上下文中的范围

java - spring 拦截器不向@RestController 服务添加 header

java - Proguard 删除 Android 应用程序中的注释