Access all @RequestHeader key value as Map in our Spring controller
Asked Answered
S

3

10

I am trying to find way through which, I can populate all Key values from @RequestHeader annotation to a Map. I tried to Google it but all I can find is a way to map each key value to one parameter.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {

    @RequestMapping(value = "/hello.htm")
    public String hello(@RequestHeader(value="User-Agent") String userAgent)

        //..
    }
}

But I want to achieve something like this.

@RequestHeader Map headerParam;

So that I can traverse the Map and use all header values as required.

Salado answered 18/7, 2016 at 12:10 Comment(2)
Have you actually tried it with a map... (and have read the original documentation ).Particiaparticipant
@M.Deinum, thanks for pointing out, I missed that somehow, Documentation seems clear.Salado
V
28

You can achieve it as follow-

@RequestMapping(value = "/hello.htm")
public String hello(@RequestHeader HttpHeaders httpHeaders){
    Map<String,String> headerMap=httpHeaders.toSingleValueMap();
    //TODO httpHeaders will have many methods
}

I hope it will help you. Thanks.

Victual answered 18/7, 2016 at 22:8 Comment(1)
Do you know what kind of map does Spring create? a hash or TreeMap?Filth
M
1

If you use spring boot below mapping would work

@RequestHeader Map<String, String> headers

@PostMapping(value = "/customer", produces = { "application/json" })
ResponseEntity<String> findName(@RequestHeader Map<String, String> headers) {

}

Mcclendon answered 26/5, 2021 at 21:27 Comment(1)
Do you know what kind of map does Spring create? a hash or TreeMap?Filth
P
0

You can simply use below code.

@RequestMapping(value = "/hello.htm")
public String hello(@RequestHeader Map<String,String> headersMap){
    // Use the parameter **headersMap.get(<Key>)** to access the values
}
Pringle answered 24/7, 2024 at 5:40 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.