我正在尝试为graphql-java-demo设置授权,因此我必须从请求中提取Cookie,以使其可用于graphql的查询(即http请求):
String cookie = request.getHeader("Cookie");
我通过添加获得请求
@Autowired
private HttpServletRequest request;
进入我的服务班级:
@Service
@Transactional
@Configuration
@WebListener
public class ServiceImpl extends RequestContextListener implements MyService {
@Autowired
NetworkService networkService;
// I had it previously when using just request.getHeader("Cookie");
// @Autowired
// private HttpServletRequest request;
@Override
public Optional<Foo> foo() {
String responseContent = networkService.send(..., getCookie());
...
}
// https://stackoverflow.com/questions/24025924/java-lang-illegalstateexception-no-thread-bound-request-found-exception-in-asp
private Optional<String> getCookie() {
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
if (attributes != null) { // it's always null
HttpServletRequest request = ((ServletRequestAttributes) attributes).getRequest();
return Optional.ofNullable(request.getHeader("Cookie"));
}
return Optional.empty();
}
}
问题是,当我启动graphql的订阅(基本上启动了websocket连接)时,我收到:
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
我看到了一些类似的questions,说我应该修改项目中没有的web.xml
,但是我确实尝试添加(使用该问题的可接受答案):
@Configuration
@WebListener
public class MyRequestContextListener extends RequestContextListener {
}
但以下行仍为我返回null:
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
那么如何在Spring Boot中使用websocket连接访问请求?