@RequestHeader annotation

@RequestHeader annotation is used to bind a specific HTTP request header to a method parameter. The header value will be injected.

Syntax:

@RequestHeader(
value = "headerName",
required = true,
defaultValue = "",
)

Attributes

  • value: The name of the HTTP request header to bind to. This attribute is also aliased to the name.
  • required: Specify true/false whether the header is required.
  • defaultValue: Default value if the header is missing.

How to Retrieve Header Values From the HTTP Request

  • Using the HttpHeaders object in the controller method
  • Using the HttpHeaders class
  • Using the HttpServletRequest object

Use Cases For @RequestHeader in Controller Methods:

  • Authentication and Authorization
  • Content Negotiation
  • Caching Control
  • Debugging and Logging

Working With HTTP Headers in Spring MVC: A Guide to @RequestHeader and @ResponseHeader

HTTP headers are key-value pairs that are sent along with HTTP requests from clients and responses from servers. Spring MVC provides various ways to access and manipulate HTTP headers in controllers.

Below are some ways to access and manipulate HTTP headers:

  • HttpServletRequest and HttpServletResponse object
  • Filter interfaces
  • WebMvcConfigurer
  • @ModelAttribute

Similar Reads

@RequestHeader annotation

@RequestHeader annotation is used to bind a specific HTTP request header to a method parameter. The header value will be injected....

Example of @RequestHeader Annotation

Java //Demonstration of @RequestHeader annotation to read  //all http header in Spring Boot application @GetMapping("/student") public User getStudent(@RequestHeader("Authorization") String authToken,            @RequestHeader("X-Student-Id") String studentId) {        // authentication logic        return studentService.getStudentById(studentId); }...

@ResponseHeader annotation

...

Example of @ResponseHeader Annotation

@ResponseHeader allows easily adding and modifying HTTP response headers from controller methods in a clean way....

Conclusion

Java //Demonstration of @ResponseHeader annotation @ResponseHeader("Cache-Control: max-age=3600") // Cache for 1 hour public String getStudent() {      return "marks>=40"; }...