Spring boot 处理复杂的 post 请求

问题描述 投票:0回答:1

有一个传入的帖子请求,如下所示:

curl --location --request POST 'http://example.com/some/path' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'prop1=prop1Value' \
--data-urlencode 'prop2[prop2Inner1]=prop2Inner1Value' \
--data-urlencode 'prop2[prop2Inner2][inner3]=inner3Value' \
--data-urlencode 'prop2[prop2Inner2][inner4]=inner4Value'

在 php 脚本中,我会自动在关联数组中获取发布请求数据,如下所示:

[
    'prop1' => 'prop1Value',
    'prop2' => [
        'prop2Inner1' => 'prop2Inner1Value',
        'prop2Inner2' => [
            'inner3' => 'inner3Value',
            'inner4' => 'inner4Value',
        ]
    ]
]

现在我正在尝试用java处理这个请求。我无法更改传入的帖子请求格式。我想我可以做几个这样的课程

@NonArgumentConstructor
@AllArgumentsConstructor
@Setter
@Getter
class MyRequest {
    private String prop1,
    private FirstInnerDto prop2;
}

@NonArgumentConstructor
@AllArgumentsConstructor
@Setter
@Getter
class FirstInnerDto {
    private String prop2Inner1;
    private SecondInnerDto prop2Inner2;
}

@NonArgumentConstructor
@AllArgumentsConstructor
@Setter
@Getter
class SecondInnerDto {
    private String inner3;
    private String inner4;
}

然后在控制器中执行类似的操作,并获取填充有请求数据的“MyRequest”类的对象:

@RequestMapping("/some/path")
public ResponseEntity<SomeResponseDto> myHandler(@ModelAttribute MyRequest request) {
    // Do anything here with 'request' object

    return ResponseEntity.status(HttpStatus.OK.value()).body(new SomeResponseDto());
}

但我收到此错误:

"Invalid property 'prop2[prop2Inner1]' of 
bean class [com.evoplay.java.myapp.Model.Dto.Request.MyRequest]: 
Property referenced in indexed property path 'prop2[prop2Inner1]' is neither an array 
nor a List nor a Map; 
returned value was [FirstInnerDto{prop2Inner1='null', prop2Inner2='null'}]"

谁能告诉我在 Spring Boot 中处理此类请求的正确方法是什么?

java spring-boot http-post
1个回答
0
投票

正如您所提到的,传入请求的格式无法更改,因此您需要在最后进行一些小的更改。

由于传入请求以数组形式出现,因此您需要捕获它 仅作为数组请求,如

@ModelAttribute MyRequest[] request

代码:

@RequestMapping("/some/path")
public ResponseEntity<SomeResponseDto> myHandler(@ModelAttribute MyRequest[] request) {
    // Do anything here with 'request' object
    return ResponseEntity.status(HttpStatus.OK.value()).body(new SomeResponseDto());
}
© www.soinside.com 2019 - 2024. All rights reserved.