Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this short tutorial, we’ll explore various ways of extracting the request headers for a Spring application. We’ll learn how to do it for a specific endpoint and, after that, we’ll create a HandlerInterceptor that intercepts all the incoming requests and extract the header.

2. Using HttpServletRequest

To be able to access information about the HTTP request, we can declare a HttpServletRequest object as a parameter for our endpoint. This allows us to see details such as the path, query parameters, cookies, and headers.

For instance, we can use HttpServletRequest to extract a custom header when we receive a request. To access a certain header, we can use the getHeader() method by specifying the key of the header:

@RestController
public class FooBarController {

    @GetMapping("foo")
    public String foo(HttpServletRequest request) {
        String operator = request.getHeader("operator");
        return "hello, " + operator;
    }

}

We can use MockMvc to send a GET request that includes the custom header. If we set the operator header as “John.Doe”, we’ll expect the response to be “hello, John.Doe”:

@Test
public void givenARequestWithOperatorHeader_whenWeCallFooEndpoint_thenOperatorIsExtracted() throws Exception {
    MockHttpServletResponse response = this.mockMvc.perform(get("/foo").header("operator", "John.Doe"))
      .andDo(print())
      .andReturn()
      .getResponse();

    assertThat(response.getContentAsString()).isEqualTo("hello, John.Doe");
}

However, if we only need one specific header from the request, declaring the whole HttpServletRequest as a parameter might be considered a violation of the Interface Segregation Principle, the “I” in SOLID.

3. Using @RequestHeader

Another simple way of accessing a request header for a specific endpoint would be to use the @RequestHeader annotation:

@GetMapping("bar")
public String bar(@RequestHeader("operator") String operator) {
    return "hello, " + operator;
}

As a result, our code is no longer coupled with the whole HttpServletRequest object and our method is now using all the data coming through as parameters.

Let’s write a similar test for this endpoint and expect the same result:

@Test
public void givenARequestWithOperatorHeader_whenWeCallBarEndpoint_thenOperatorIsExtracted() throws Exception {
    MockHttpServletResponse response = this.mockMvc.perform(get("/bar").header("operator", "John.Doe"))
      .andDo(print())
      .andReturn()
      .getResponse();

    assertThat(response.getContentAsString()).isEqualTo("hello, John.Doe");
}

4. Using HandlerInterceptor

For more complex use cases, we can use an HandlerInterceptor object. The advantage is that it can intercept all incoming requests and extract the value of the header.

Moreover, we can wrap the value of the header in a Spring bean with a request scope and inject it into different components where it might be needed.

Firstly, let’s wrap the operator name into an object:

public class OperatorHolder {
    private String operator;
    // getter and setter
}

Now, let’s declare it as a bean using @Bean. The operator might be different from one request to another, so we should set the bean scope to SCOPE_REQUEST:

@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public OperatorHolder operatorHolder() {
    return new OperatorHolder();
}

After that, we’ll need to create a custom implementation of the HandlerInterceptor interface, and override the preHandle() method:

public class OperatorInterceptor implements HandlerInterceptor {
    private final OperatorHolder operatorHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String operator = request.getHeader("operator");
        operatorHolder.setOperator(operator);
        return true;
    }
    // constructor
}

As a result, the request is intercepted, the operator header is extracted, and the OperatorHolder bean is updated.

Lastly, we need to add our custom interceptor to Spring MVC’s InterceptorRegistry. We can do it through a configuration class that implements WebMvcConfigurer and overrides addInterceptor():

@Configuration
public class HeaderInterceptorConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(final InterceptorRegistry registry) {
        registry.addInterceptor(operatorInterceptor());
    }

    @Bean
    public OperatorInterceptor operatorInterceptor() {
        return new OperatorInterceptor(operatorHolder());
    }
}

To access the operator now, we only need to inject the  OperatorHolder bean and call the getOperator() method:

@RestController
public class BuzzController {
    private final OperatorHolder operatorHolder;

    @GetMapping("buzz")
    public String buzz() {
        return "hello, " + operatorHolder.getOperator();
    }
    // constructor
}

5. Conclusion

In this article, we explored various ways of accessing a custom header for incoming HTTP requests.

Initially, we learned how to do it for a specific endpoint, through HttpServletRequest and @RequestHeader. After that, we saw how HandlerInterceptor allows us to extract the header from all the incoming requests and offers a more generic solution.

As always, the complete source code for the tutorial is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.