Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW