Open In App

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

Last Updated : 17 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

@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

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);
}


The headers will be passed to the authToken and studentId parameters respectively. The method then validates the auth token and returns the student based on the studentId.

Note: To access multiple headers, you can use a Map, MultiValueMap, or HttpHeaders object as the parameter type.

@ResponseHeader annotation

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

Syntax:

@ResponseHeader(
name = "headerName",
description = "",
response = String.class,
responseContainer = ""
)

Attributes:

  • name: The name of the HTTP response header to add.
  • description: An optional description of the header’s purpose or usage.
  • response: The type of the header value. This is typically a String, but it can be any Java type.
  • responseContainer: An optional indication of whether the header value is wrapped in a container, such as a list or set.

How to add/modify headers in the HTTP response:

  • Using the HttpServletResponse object
  • Using the HttpHeaders class
  • Using the ResponseEntity class

Use cases for @ResponseHeader in controller methods:

  • Security Enhancements
  • Customizing Response Metadata
  • Custom Response Handling
  • Link Management

Example of @ResponseHeader Annotation

Java




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


@ResponseHeader annotation indicates that the “Cache-Control” header should be added to the response generated by the “getStudent” method. The response can be cached for up to one hour before needing to be refreshed, according to the “max-age=3600” directive.

Note: To add multiple headers, you can use a Map, MultiValueMap, or HttpHeaders object as the annotation argument.

Conclusion

In summary, @RequestHeader and @ResponseHeader provide an elegant way to work with HTTP headers in Spring MVC. They simplify access to request headers and enable convenient manipulation of response headers, contributing to well-structured and informative responses.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads