Skip to main content

SpringBoot : How to read Header from Request and bind to variable

How to read Headers in Spring Boot Controller


Suppose we have a controller and want to bind the Headers to a variable, then we can do the following

 
@RequestHeader(value = "Accept-Language", defaultValue = "en") String locale


This will bind the Header Accept-Language, to the variable locale.
  • value="" It defines the name of the header to bind to the variable
  • required= boolean It tells if this is mandatory header or not. default value is true
  • defaultValue ="" It can be used to give a default value if the header is not present.
Similarly you can bind Custom Headers like shown below

     // String
@RequestHeader(value = "X-My-String-Header", defaultValue = "Hello World") String h1
// Long
@RequestHeader(value = "X-My-Long-Header", defaultValue = 212) Long h2


Do not use "_" underscore in header key or values, because they get neglected while http calls.

Comments