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.
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