java从Spring Boot应用程序的服务层中的请求获取标头 1 年,6 月 Questions & Answers 16952 在SpringBoot中,是否有任何方法可以在任何应用程序点从请求中获取头文件? 一些静态的东西会很棒 请注意@RequestHeader不适合我,因为我需要服务层上的这个值
# 1 楼答案 我之前搜索过同一个问题,我发现您可以在RestController方法中使用头参数,如您所说的@RequestHeader。那么,为什么不将它们引导到您的服务层方法中呢: @Autowired ServiceLayerObj serviceLayerObj; ... @RequestMapping public YourReturnObj someRestServiceMethod( @RequestBody SomeObj body, @RequestHeader(value = "username") String username ){ return serviceLayerObj.yourServiceLayerMethod(body,username); }
# 2 楼答案 您可以在服务层中注入HttpServletRequest对象,如下所示: @Autowired HttpServletRequest request; private void method() { request.getHeader("headerName"); } 但是请记住,beanHttpServletRequest具有HTTP请求范围。因此,不能将其注入异步方法等,因为它将throw Runtime Exception 希望能有帮助
# 1 楼答案
我之前搜索过同一个问题,我发现您可以在RestController方法中使用头参数,如您所说的@RequestHeader。那么,为什么不将它们引导到您的服务层方法中呢:
# 2 楼答案
您可以在服务层中注入
HttpServletRequest
对象,如下所示:但是请记住,bean
HttpServletRequest
具有HTTP请求范围。因此,不能将其注入异步方法等,因为它将throw Runtime Exception
希望能有帮助