Specifying @RequestHeader once for all controllers in Spring Boot app

你。 提交于 2020-12-30 08:57:31

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/31497786/specifying-requestheader-once-for-all-controllers-in-spring-boot-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!