Spring-framework: Provide mechanism to map request parameters to fields of DTO object

Created on 6 Jun 2019  路  4Comments  路  Source: spring-projects/spring-framework

This is more of a feature request:

If I have a bunch of request parameters in my service method, I would like all of them to be grouped in a DTO object.
For instance, if I have a following method:

@GetMaping
public ResponseEntity<?> listEntities(
        @RequestParam(value = "page-number", defaultValue = "0") @Min(0) Integer pageNumber,
        @RequestParam(value = "page-size", defaultValue = "100") @Min(1) Integer pageSize, ... )

Disregard the names of the parameters. What is important here, that there could be plenty of those and some of them might be mutually exclusive. Since they might be mutually exclusive, I would like to validate the state of so-called RequestParamsDTO. Ideally, I would like to create a custom validator (using hibernate validator) and then annotate the argument of type RequestParamsDTO with the proper validation annotation.

I know that there is a mechanism that even without the @RequestParam annotation spring will make its best to match arguments to the properties of a bean, in this case, RequestParamsDTO object.

But the problem lays in the naming of my request parameters:
some of them have dashes in the name, like page-number. I cannot create a field in my RequestParamsDTO with that name for the obvious reasons.

And it seems there is no mechanism to map those request parameters to the fields of the DTO.

It would be nice to have a mapping mechanism for such case or allow @RequestParam annotation on class fields.

superseded

Most helpful comment

Actually, there is a way of doing that:
@ConstructorProperties annotation allows to group request params into a DTO.
Check accepted answer: https://stackoverflow.com/questions/56468760/how-to-collect-all-fields-annotated-with-requestparam-into-one-object

@imochurad that's cool! Although not as clean as your original proposal.

However, I think it doesn't work for headers.

All 4 comments

It would also be nice to have the same functionality but also for headers (analogous to the @RequestParam case but with @RequestHeader).

Actually, there is a way of doing that:
@ConstructorProperties annotation allows to group request params into a DTO.
Check accepted answer: https://stackoverflow.com/questions/56468760/how-to-collect-all-fields-annotated-with-requestparam-into-one-object

Actually, there is a way of doing that:
@ConstructorProperties annotation allows to group request params into a DTO.
Check accepted answer: https://stackoverflow.com/questions/56468760/how-to-collect-all-fields-annotated-with-requestparam-into-one-object

@imochurad that's cool! Although not as clean as your original proposal.

However, I think it doesn't work for headers.

This is now superseded by #23618.

Was this page helpful?
0 / 5 - 0 ratings