Reputation: 176
In one of my app I have many endpoints with the same set of headers:
@RequestHeader("foo") String foo,
@RequestHeader("bar") String bar,
@RequestHeader("baz") String baz,
and in each controller method I am creating my custom dto based on those headers:
MyDto myDto = new MyDto(foo, bar, baz);
To avoid duplicates and adding/removing one header 50 times to each method, I want to have something like interceptor class that will take HttpHeaders
and will transform it MyDto
only once, so then I want to be able to replace all request headers in controller methods by simply MyDto myDto
created behind the scenes.
I tried to find solution, but didn't found anything.
Actual:
@PostMapping("/myEndpoint")
public MyResponse myEndpoint(@RequestHeader("foo") String foo,
@RequestHeader("bar") String bar,
@RequestHeader("baz") String baz,
@RequestBody MyRequest myRequest) {
MyDto myDto = new MyDto(foo, bar, baz);
myService.doSomething(myDto);
...
}
Expected:
@PostMapping("/myEndpoint")
public MyResponse myEndpoint(MyDto myDto,
@RequestBody MyRequest myRequest) {
myService.doSomething(myDto);
...
}
I also have a method for it:
public MyDto transform(HttpHeaders httpHeaders) {
String foo = getHeader(httpHeaders, "foo");
String bar = getHeader(httpHeaders, "bar");
String baz = getHeader(httpHeaders, "baz");
return new MyDto(foo, bar, baz);
}
private String getHeader(HttpHeaders httpHeaders,
String key) {
return Optional.ofNullable(httpHeaders.get(key))
.map(Collection::stream)
.orElseGet(Stream::empty)
.findFirst()
.orElse(null);
}
But I don't know when I can call it to make it runnable on each request.
Upvotes: 1
Views: 607
Reputation: 3724
I was about to say , write and register a custom HandlerInterceptor
. It would allow you to access the headers, but the problem is you won't get access to the converted @RequestBody object - at least, as far as I know. I don't think this can easily be done.
Upvotes: 1