【问题标题】:How to inject HttpServletRequest or Session from CDI如何从 CDI 注入 HttpServletRequest 或 Session
【发布时间】:2016-10-27 10:01:38
【问题描述】:

我有一个类在我的休息服务中作为类生产者执行:

public class WebResources{


    @Produces
    @RequestScoped
    public FacesContext produceFacesContext() {
        return FacesContext.getCurrentInstance();
    }

    @Produces
    public Logger produceLog(InjectionPoint injectionPoint) {
        return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
    }   
}

现在我希望通过使用 HttpServletRequest 或 HttpSession 作为参数来生成我的对象。像这样的:

@Produces
@RequestScoped
public MyObject getSecurityContext(InjectionPoint injectionPoint)
{
    HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
    return Utils.getMyObject(request);
}

我在部署阶段收到的错误如下:

错误 [org.jboss.as.cli.CommandContext] {"JBAS014671: 失败的服务" => {"jboss.deployment.unit.\"zuora.ear\".WeldStartService" => "org.jboss.msc .service.StartException in service jboss.deployment.unit.\"zuora.ear\".WeldStartService: 无法启动服务 引起:org.jboss.weld.exceptions.DefinitionException: WELD-001406 无法注入 [方法] 的 [参数 1] @Produces @RequestScoped public it.infocert.zuora.rest.util.WebResources.getSecurityContext(InjectionPoint) 在非@Dependent 作用域 bean"}} {"JBAS014671: 失败的服务" => {"jboss.deployment.unit.\"zuora.ear\".WeldStartService" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"zuora .ear\".WeldStartService: 启动服务失败 原因:org.jboss.weld.exceptions.DefinitionException: WELD-001406 无法注入 [方法] @Produces @RequestScoped public it.info 的 [参数 1]

【问题讨论】:

  • 据我所知,单独使用 Weld 无法注入 Request,我知道和使用的方式是来自 deltaspike 的 RequestResponseHolderFilter。通过使用此过滤器,您可以注入带有限定符 @Deltaspike 的 HttpRequest。欲了解更多信息,请参阅deltaspike.apache.org/documentation/servlet.html。如果你不想/不能使用 deltaspike,你可以查看它的 servlet 模块源代码。这很简单。您需要获取每个请求并将其保存在 ThreadLocal 变量中。
  • 顺便说一句:您可以使用 CDI >= 1.1 注入 HttpServletRequest

标签: jakarta-ee jboss cdi


【解决方案1】:

您应该从方法签名中删除InjectionPoint 参数。如果您正在生成请求范围的 bean,则您不能使用 InjectionPoint,因为多个注入点将获得相同的(请求范围的)实例。您没有在代码中使用注入点,因此删除它是安全的。

【讨论】:

  • 这对我来说没问题,但是我如何引用 HttpServletRequest 呢?
  • 在您的getSecurityContext 中,您正在从 FacesContext 获取请求。那么为什么需要 InjectionPoint 呢?
  • 其实sn-p是不行的; FacesContext currentInstance = FacesContext.getCurrentInstance();返回空
  • 如果在 JSF 生命周期开始之前调用了生产者,就会发生这种情况。如果您使用 CDI >= 1.1,您可以简单地注入 HttpServletRequest。如果您使用的是 CDI 1.0,则可以使用 DeltaSpike Servlet 模块,该模块在 CDI 1.0 环境中启用注入。 deltaspike.apache.org/documentation/servlet.html
猜你喜欢
  • 2016-11-21
  • 2015-07-14
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多