user6947497
user6947497

Reputation: 23

Java Spring Convert whole GET Request to Custom DTO

According to the Spring documentation, you can receive all GET parameters in a map like so:

@GetMapping
public final ReturnType getAll(@RequestParam MultiValueMap<String, String> allRequestParams) {
    ...
}

Is it possible (and how) to also accept a custom Java object instead (for which a custom Converter exists via subclassing GenericConverter) in such a way that the Converter gets the whole request map for construction of its DTO object?

@GetMapping
public final ReturnType getAll(@RequestParam CustomDTO customObj) {
    [...]
}

[...]

@Component
public class CustomDTOConverter implements GenericConverter {

    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        // Allow MultiValueMap.class to CustomDTO.class
        [...]
    }

    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {

        final MultiValueMap<String, String> requestMap = (MultiValueMap<String, String>) source;
        // Construct CustomDTO from the requestMap
    }
}

Trying the above snippet will fail, complaining that there is no parameter customObj present.

Upvotes: 1

Views: 3135

Answers (1)

Nick
Nick

Reputation: 3951

For convert get parameters to java object use method parameter without annotations. CustomDto must have setters.

@GetMapping
public final ReturnType getAll(CustomDTO customObj) {
    ...
}

class CustomDto {
    int x;
    String s;

    public void setX(int x) {
        this.x = x;
    }

    public void setS(String s) {
        this.s = s;
    }
}

Url example:http://example.com/test?x=123&s=abc

Upvotes: 2

Related Questions