Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 792
JRishi Avatar asked Jul 18 '16 12:07

JRishi


2 Answers

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.

like image 160
sanjeevjha Avatar answered Dec 21 '22 08:12

sanjeevjha


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) {

}

like image 32
Palla Avatar answered Dec 21 '22 08:12

Palla