gpt4 book ai didi

java - 使用 @RequestScoped bean 将 header 值从 Web 层传递到 EJB?

转载 作者:行者123 更新时间:2023-12-02 20:08:08 24 4
gpt4 key购买 nike

我应该将来自请求的 HTTP header 附带的一些信息传递给 EJB,但我不想添加参数并将它们传递到我需要的任何地方。所以我使用 RequestScoped bean 来保存我的 header 值。这个实现可以吗,还是我误解了 @RecuestScoped beans 的概念?

首先,我使用拦截器 (Resteasy) 获取 header ,并将它们保存到我的请求范围 bean 中:

@Provider
@ServerInterceptor
public class SomeInterceptor implements PreProcessInterceptor {

@Inject
ApplicationRequestContext appContext;

@Override
public ServerResponse preProcess(HttpRequest request, ResourceMethod resourceMethod)
throws Failure, WebApplicationException {
List<String> values = request.getHttpHeaders().getRequestHeader("Some-Header");
if(values != null && values.size() > 0) {
appContext.setSomeHeader(values.get(0));
}
return null;
}
}

这是 bean :

@RequestScoped
public class ApplicationRequestContext implements Serializable {
private String someHeader;

public void setSomeHeader(String someHeader) {
this.someHeader = someHeader;
}

public String getSomeHeader() {
return someHeader;
}
}

然后我可以从我的 EJB 访问该值(每个请求都不同):

@Stateless
public class CheckInWorkflow {

@Inject
ApplicationRequestContext appContext;

public void someEjbMethod() {
doSomethingWithThisHeaderValue(appContext.getSomeHeader());
}
}

基于@RequestScoped的描述这应该按预期工作:

The request scope is active:

  • during the service() method of any servlet in the web application, during the doFilter() method of any servlet filter and when the container calls any ServletRequestListener or AsyncListener,
  • during any Java EE web service invocation,
  • during any remote method invocation of any EJB, during any asynchronous method invocation of any EJB, during any call to an EJB timeout method and
  • during message delivery to any EJB message-driven bean, and during any message delivery to a MessageListener for a JMS topic or queue obtained from the Java EE component environment.

最佳答案

实现是正确的,但似乎是使用副作用进行了不必要的优化。

关于java - 使用 @RequestScoped bean 将 header 值从 Web 层传递到 EJB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34489956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com