Reputation: 173
Good Morning,
I have a RestController controller where I have a GetMapping using a header. If that header does not come with any value, I want to route to a default method, ¿is there any way? ¿Is there any way to set the value of a default header when the rest Client dont send it?
@RestController
@RequestMapping("/api/demo")
@Log4j2
public class RestDemoController{
@GetMapping( value = "/version", headers = "x-api-version=v.1.0")
public String getHeaderValue(@RequestHeader(value=ApiVersionConstans.API_VERSION_HEADER_CODE) String version) {
log.debug("Returning version header");
return ApiVersionConstans.API_VERSION_HEADER_CODE;
}
@GetMapping(value = "/version", headers = "x-api-version=v.1.0_default")
public String getAnoherHeader(@RequestHeader(value=ApiVersionConstans.API_VERSION_HEADER_CODE) String version) {
log.debug("Looking for exisiting tokens");
return "This is another header";
}
}
Regards
Upvotes: 0
Views: 4678
Reputation: 638
Please try this:
@GetMapping("/version")
public String getDefaultHeader(@RequestHeader(value=ApiVersionConstans.API_VERSION_HEADER_CODE, defaultValue="your default value") String version) {
// ...
return "This is default header";
}
When you set @RequestHeader#defaultValue
, the header is not required and its value is set to version
when the header is missing.
I think javadoc of @RequestHeader
is helpful for you:
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestHeader.html#required--
Upvotes: 2