i'm using Spring Boot and need to access multiple values from the request headers, the problem is that @RequestHeader
it only accepts a single property at a time. Instead of declaring individual properties each time, I'd like to convert this into a DTO for better organization.
Using query params i can use @ModelAttribute filters: FiltersDTO
and that works, Is there an equivalent approach for handling request headers, where I can map them to a DTO directly?
That is my code:
@PostMapping("blah")
suspend fun blah(
@RequestHeader userInfo: UserHeaderDto
) {}
data class UserHeaderDto(
val userId: Long,
val name: String
){}
I receive the exception:
org.springframework.web.bind.MissingRequestHeaderException: Required request header 'userInfo' for method parameter type UserHeaderDto is not present
Try using a Map<String, String> headers
, and then you can have a class called RequestHeadersExtractor
that encapsulates the logic of extracting the request headers.
Take a look at the below example:
@Service
@Slf4j
public class RequestHeadersExtractor {
// declare your request headers
public static final String USER_ID = "user-id";
public static final String NAME = "name";
public SampleDto extractHeaders(Map<String, String> headers) {
// populate your dto here with the fields and return it.
}
}
Then you can call extractHeaders
from your controller's method.