Java Spring将整个GET请求转换为自定义DTO

时间:2016-10-10 06:11:09

标签: java spring spring-mvc spring-boot

根据Spring文档,您可以在地图中接收所有GET参数,如下所示:

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

是否有可能(以及如何)接受自定义Java对象(通过子类化Converter为其存在自定义GenericConverter),以便Converter获取整个请求映射构建DTO对象?

@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
    }
}

尝试上述代码段会失败,抱怨没有参数customObj

1 个答案:

答案 0 :(得分:0)

对于将get参数转换为java对象,请使用不带注释的方法参数。 CustomDto必须有setter。

@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;
    }
}

网址示例:http://example.com/test?x=123&s=abc