TryThis
TryThis

Reputation: 374

Spring Binding Request Parameters to Java Record

I am trying to bind several request parameters to a Java record. It works if the parameters are named exactly like the record fields. Is there a way to bind to differently named fields, and have default values?

Example Controller

@GetMapping("/invoices")
public InvoicesResponseDto queryInvoiceByDate(InvoicesByDateRequestDto requestDto) {
   ...
}

And what I was attempting to do in the Java record:

public record InvoicesByDateRequestDto(
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate from,
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate to,
        @RequestParam(value = "restricted", defaultValue = "true") Boolean isRestricted)
{}

When I do this the to and from fields bind correctly. However, the isRestricted is not bound when the parameter is passed as "restricted", but is bound when it is "isRestricted". Also, the defaultValue is not working.

I am assuming @RequestParam is not valid for this use case. Is there an alternative to map to different names, and support default values?

Upvotes: 1

Views: 766

Answers (0)

Related Questions