Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying @RequestHeader once for all controllers in Spring Boot app

I have a Spring Boot app with multiple controllers serving various REST methods. Each of the methods require that the same header parameter be defined. Is there a way to specify something like the following one time for all controller methods?

public ResponseEntity get(@RequestHeader(value="NAME", required = true) String name, ...) {
   ...
}

Thanks.

like image 663
balduncle Avatar asked Jul 19 '15 03:07

balduncle


People also ask

How can you obtain a RequestHeader in a controller method?

First, we used the @RequestHeader annotation to supply request headers to our controller methods. After checking out the basics, we took a detailed look at the attributes for the @RequestHeader annotation. The example code is available over on GitHub.

How spring determines your controller classes?

Spring Controller annotation is typically used in combination with annotated handler methods based on the @RequestMapping annotation. It can be applied to classes only. It's used to mark a class as a web request handler. It's mostly used with Spring MVC applications.


1 Answers

You can probably achieve this using @ModelAttribute, like this:

public class Something {
  private name;
  //...
}

@ModelAttribute("something")
public Something addSomething(@RequestHeader(value="NAME", required = true) String name) {
  return new Something(name);
}

@RequestMapping("/something")
public ResponseEntity get(@ModelAttribute Something something) {
  //...
}

You can implement the @ModelAttribute populating method in a single Controller or in a @ControllerAdvice class, in order to assist multiple controllers. See reference documentation.

like image 176
Brian Clozel Avatar answered Sep 23 '22 06:09

Brian Clozel