Ekansh Rastogi
Ekansh Rastogi

Reputation: 2536

How can i use an Interceptor to set a field in Spring Controller

i have a controller like following

@RestController
class TestController{
 private String country;

  public String m1(){}
  public String m2(){}
  public String m3(){}
  public String m4(){}

}

All the methods m1 to m4 needs the country that is taken from the header.

is there a method to do that for all the methods of this controller.

I tried using Interceptor but, i am not able to get country after the interceptor execution is over. that is i always get country a null

Upvotes: 0

Views: 480

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280138

Spring MVC provides @RequestHeader which

indicates that a method parameter should be bound to a web request header

Annotate your handler method parameter appropriately

@RequestMapping("/somePath")
public ReturnType example(@RequestHeader("country-header") String country) {
    // use it
}

The Spring MVC stack will extract the header value and use it to invoke your handler method.

Upvotes: 2

Related Questions