SpringBoot : Request Header

SpringBoot : Request Header

Motivation

I wanted to understand how headers works in springboot

Simple Example

    @GetMapping("/testheader")
    public String testHeader(@RequestHeader("iv-user") String ivUser) {

        System.out.println("Currently logged in user "+ivUser);

        return "testing header";
    }

in the above mentioned code we are sending the header iv-user using postman

image.png

What if the required header is not present

if the required header is not present in the postman we can see the error 400 Bad Request but in the sprint boot we are seeing the error

.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingRequestHeaderException: Required request header 'iv-user' for method parameter type String is not present]

Lets understand optional headers

There is a property we can set required=false in this case if the header is not sent from the frontend it will not throw the bad request error

@GetMapping("/testheader")
    public String testHeader(@RequestHeader(value="iv-user", required = false) String ivUser) {

        System.out.println("Currently logged in user "+ivUser);

        return "testing header";
    }