I have a web application with 10 controllers. Each controller represents an endpoint. Each controller has various API operations. I have used basic authentication for the API methods. I have used @RequestHeader in these methods to get the header and resolver username from it. I was wondering if I can get the header in the class level and provide header to all the methods in a Controller class.

I have tried to use the @RequestHeader in class level as instance variable but it does not resolve.

public class ClientRestController {

    @ApiOperation(value = "Client Search", authorizations = {@Authorization (value="basicAuth")})
    public ResponseEntity<ClientSearchResponse> getClients(
        @RequestHeader HttpHeaders httpHeaders,
    //code to use httpHeaders 



I want to able to share the httpHeaders on the controller level and use it to in all the methods in the class because I only need the username from it.

1 Answers

computatma On

I was able to get the required header using HandlerInterceptor. My question is, is it safe to have instance variable headerMap in this class.

I am passing value from headerMap to service class and will it be safe when serving concurrent requests?

public class RestRequestInterceptor implements HandlerInterceptor {

    private Map<String,String> headerMap;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
    //  pre-handle logic, set header map from request.

   // other @Override methods