Sobes.tech
Senior

How to read a specific header (for example, badge number) in a controller?

sobes.tech AI

Answer from AI

In a Java Spring controller, to read a specific HTTP header (for example, a badge number), you can use the @RequestHeader annotation.

Example:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/some-endpoint")
    public String handleRequest(@RequestHeader("X-TabNumber") String tabNumber) {
        // tabNumber contains the value of the "X-TabNumber" header
        return "Badge number: " + tabNumber;
    }
}

If the header is optional, you can specify the parameter required = false and set a default value:

@RequestHeader(value = "X-TabNumber", required = false) String tabNumber

Thus, @RequestHeader makes it easy to retrieve the desired header from an HTTP request within a controller method.