标签: cdi

如何在PhaseListener中访问@Named bean?

我们使用JBoss 7.1,MySQL/PostgreSQL DB,JSF 2.0和CDI bean.

我必须通过登录名和密码实现基于DB的身份验证.我们有一个管理(管理)门户网站.当客户端在未登录的情况下打开受限页面时,login.*如果客户端未登录,则应将请求重定向到页面.

我试图通过使用a来做到这一点PhaseListener.我可以登录和注销,但是当我尝试打开另一个页面时遇到了一个问题:我无法@Named("user") public class UserManagerPhaseListener课程中获得bean .我试图通过使用FacesContext和EL 来获得它,这一切都没有帮助我.

UserManager验证的登录名和存储登录用户的current财产.在每个请求,我想检查PhaseListenerif #{user.current}是不是null.但我无法得到#{user}豆子PhaseListener.

我怎样才能得到一个@Named在豆beforePhase()afterPhase()


更新:这是我到目前为止的尝试:

private boolean loggedIn( FacesContext context ) throws IOException, ServletException
{
    LOGSTORE.debug( "loggedIn().2 " );

    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();

//  ELContext elContext = FacesContext.getCurrentInstance().getELContext();
//  UserManager userManager = (UserManager) …
Run Code Online (Sandbox Code Playgroud)

jpa named cdi jsf-2 phaselistener

1
推荐指数
1
解决办法
3881
查看次数

NullPointer与Arquillian CDI测试

我正在尝试从本教程中运行一个简单的CDI测试.下面是我的JUNIT和POM.不确定错误是什么.感谢任何帮助.

错误

java.lang.NullPointerException
    at com.aravind.jee6.cdi.basic.GreeterTest.greet(GreeterTest.java:32)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.jboss.arquillian.junit.Arquillian$6$1.invoke(Arquillian.java:270)
    at org.jboss.arquillian.container.test.impl.execution.LocalTestExecuter.execute(LocalTestExecuter.java:60)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:135)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:115)
    at org.jboss.arquillian.core.impl.EventImpl.fire(EventImpl.java:67)
    at org.jboss.arquillian.container.test.impl.client.protocol.local.LocalContainerMethodExecutor.invoke(LocalContainerMethodExecutor.java:50)
    at org.jboss.arquillian.container.test.impl.execution.RemoteTestExecuter.execute(RemoteTestExecuter.java:120)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:135)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:115)
    at org.jboss.arquillian.core.impl.EventImpl.fire(EventImpl.java:67)
    at org.jboss.arquillian.container.test.impl.execution.ClientTestExecuter.execute(ClientTestExecuter.java:57)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at …
Run Code Online (Sandbox Code Playgroud)

java cdi jboss-weld jboss-arquillian weld

1
推荐指数
1
解决办法
3414
查看次数

CDI-Interceptor:从拦截的方法获取参数

我有一个界面

@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE })
public @interface LoggingInterceptorBinding {

}
Run Code Online (Sandbox Code Playgroud)

和一个班级:

@LoggingInterceptorBinding
@Interceptor
public class LoggingInterceptor implements Serializable {

@AroundInvoke
public Object onMethodCall(InvocationContext context) throws Exception {
    try {
        System.out.println("Log before Method");
        return context.proceed();
    } finally {
        System.out.println("Log after Method");
    }

}
Run Code Online (Sandbox Code Playgroud)

和一个带注释的方法:

@LoggingInterceptorBinding
public void sayHello(String name)
Run Code Online (Sandbox Code Playgroud)

是否可以在拦截器"onMethodCalls"-method中从sayHello获取参数"name"?

java cdi

1
推荐指数
1
解决办法
2042
查看次数

@ConversationScope bean不保留引用值

我正在尝试实现Twitter登录过程.在登录过程中,用户需要被重定向到Twitter网站以输入他/她的凭证,然后他/她将被重定向到我的网站URL.在第一次重定向之前,应该在请求之间存储和保留RequestToken对象(Twitter4J库)的实例.

为此,我决定使用ConverstaionScoped bean,但遗憾的是,请求之间不保留引用的值.

这是我的JSF页面:

twitter.xhtml:

<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      >

    <f:event listener="#{twitterLoginPageController.login()}" type="preRenderView" />

</html>
Run Code Online (Sandbox Code Playgroud)

twitterRedirect.xhtml:

<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      >

    <f:event listener="#{twitterLoginPageController.onRedirect(param.oauth_token, param.oauth_verifier)}" type="preRenderView" />

</html>
Run Code Online (Sandbox Code Playgroud)

我的Twitter登录控制器:

@Named
@ConversationScoped
public class TwitterLoginPageController implements Serializable {


    @Inject
    private Conversation conversation;

    // These objects should be retained between requests
    Twitter twitter;
    RequestToken requestToken;

    public void login() {

        try {
            twitter = new TwitterFactory().getInstance();
            requestToken = twitter.getOAuthRequestToken("...");


            conversation.begin();
            conversation.setTimeout(30000);
            // Navigate to Twitter here
        } catch (TwitterException ex) {
             ...
        }

    } …
Run Code Online (Sandbox Code Playgroud)

ejb cdi twitter4j jsf-2 conversation-scope

1
推荐指数
1
解决办法
320
查看次数

Glassfish 4,CDI中的简单示例因WELD-001408不满意的依赖性而失败

我是CDI的新手.这是我的第一个例子,我正在尝试运行它.搜索过互联网后,我编写了以下代码:我想要注入的类

public class Temp {

public Temp(){

}

public String getMe(){
    return "something";
}
}
Run Code Online (Sandbox Code Playgroud)

Servlet的

@WebServlet(name = "NewServlet", urlPatterns = {"/NewServlet"})
public class NewServlet extends HttpServlet {

@Inject
public Temp temp;

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        out.println("<body>");
        out.println("<h1> Here it is"+temp.getMe()+ "</h1>");
        out.println("</body>");
    }
}
...
Run Code Online (Sandbox Code Playgroud)

但是我必须跟踪glassfish 4中的错误:

org.jboss.weld.exceptions.DeploymentException:WELD-001408在注入点[[BackedAnnotatedField] @Inject private xxx.example.NewServlet.temp]中带有限定符[@Default]的[Temp]类型的不满意依赖项

我究竟做错了什么?

java dependency-injection glassfish java-ee cdi

1
推荐指数
1
解决办法
7095
查看次数

在运行时阅读装饰有特定注释的所有类

我需要在运行时阅读所有装饰有特定注释(例如@HttpSecurity)的类(接口)。扫描后,我希望阅读和解析装饰有注释的类的字段(枚举字段)。例如。

@HttpSecurity
public interface MyHttpSecurityConfig {

public enum secure {
    @Path(pathGroup = "/*", pathName = "")
    @Authc
    @Form(errorPage = "/error.html", loginPage = "/login.html", restoreOriginalRequest = "")
    @Authz
    @AllowedRoles(roles = { "roleA", "roleB" })
    @AllowedGroups(groups = { "groupA" })
    @AllowedRealms(realms = { "realmA" })
    @Expressions(expressions = { "#{identity.isLoggedIn()}" })
    Admin
  }
}
Run Code Online (Sandbox Code Playgroud)

可能存在一个或多个用@HttpSecurity装饰的类/接口。我的第一个要求是获取所有此类,第二个要求是通过读取注释及其在枚举字段上修饰的值来构建HttpSecurityBuilder。第二个要求很好,可以使用反射消除。但是,我的问题是第一个要求。我想用JavaSE核心实现第一个要求,即不使用任何外部依赖项,例如google Reflections。如有必要,可以假定我们具有要在其中扫描类的程序包名称。这是我做过什么用CDI

java reflection annotations cdi

1
推荐指数
1
解决办法
995
查看次数

如何使用CDI从.properties文件中@Inject值

如何从属性文件中注入一些值?我有一个带有一些键和值的.properties文件,我想注入那些用于某些类的东西,例如:

@Inject(file = "/WEB-INF/abc.properties",key ="path")
private String path;
Run Code Online (Sandbox Code Playgroud)

因此,当我使用路径时,它具有属性文件中的值,而不是彻底读取属性和获取值的整个过程.

dependency-injection properties cdi

1
推荐指数
1
解决办法
1904
查看次数

Arquillian:多次尝试注册相同的Observer,ServerSetupObserver

我正在尝试使用wildfly配置arquillian但是在运行测试的过程中出现以下错误:

    java.lang.RuntimeException: Could not create new instance of class org.jboss.arquillian.test.impl.EventTestRunnerAdaptor
    at org.jboss.arquillian.test.spi.SecurityActions.newInstance(SecurityActions.java:165).......
Caused by: java.lang.reflect.InvocationTargetException: null
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    ...........
Caused by: java.lang.RuntimeException: Could not create new instance of class org.jboss.arquillian.core.impl.ManagerImpl
    at org.jboss.arquillian.core.spi.SecurityActions.newInstance(SecurityActions.java:165)
    at .................
Caused by: java.lang.reflect.InvocationTargetException: null
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at ...............
Caused by: java.lang.RuntimeException: Could not create and process manager
    at org.jboss.arquillian.core.impl.ManagerImpl.<init>(ManagerImpl.java:105)......
Caused by: java.lang.IllegalArgumentException: Attempted to register the same Observer: org.jboss.as.arquillian.container.ServerSetupObserver multiple times, please check classpath for conflicting jar versions …
Run Code Online (Sandbox Code Playgroud)

junit ejb cdi jboss-arquillian wildfly-8

1
推荐指数
1
解决办法
1883
查看次数

为什么在任何其他托管bean之前创建JSF转换器?

JSF Converter似乎是在xhtml页面上的任何其他托管bean之前调用的.它甚至可以rendered=falseh:selectOneMenu组件上创建.

我已经创建了3个托管bean来测试初始化​​序列,并且托管bean按顺序初始化它们出现在xhtml中,但在它们之前,尽管是最后一个创建了JSF转换器.

形成

<h:form>
    <h:inputText value="#{creationTime1.string1}"/>
    <h:inputText value="#{creationTime3.string3}"/>
    <h:inputText value="#{creationTime2.string2}"/>
    <h:selectOneMenu value="#{creationTime1.competitor}" rendered="false" converter="#{testConverter}" >
        <f:selectItem itemValue="#{null}" itemLabel="#{msg.none}" />
        <f:selectItems value="#{creationTime1.competitorList}" var="competitor" itemValue="#{competitor}"
                       itemLabel="#{competitor.idCompetitor}"/>
    </h:selectOneMenu>
    <h:commandButton value="GO" action="#{creationTime1.submit}"/>
</h:form>
Run Code Online (Sandbox Code Playgroud)

变流器

@Named(value = "testConverter")
@ViewScoped
public class TestConverter implements Converter, Serializable {

    @PostConstruct
    private void init() {
        System.out.println(System.currentTimeMillis() +  " || TestConverter init");
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        ...
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) { …
Run Code Online (Sandbox Code Playgroud)

jsf converter cdi

1
推荐指数
1
解决办法
304
查看次数

通过<jsp:useBean>访问的会话范围的CDI bean似乎与servlet不同

我想将CDI SessionScoped bean注入JSP页面.

import javax.enterprise.context.SessionScoped;
import java.io.Serializable;

@SessionScoped
public class UserSessionBean implements Serializable {

    private String email = "email";

    public UserSessionBean(){}

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我以这种方式使用bean时,它工作正常,我在JSP页面上看到了初始值.

<jsp:useBean id="userSessionBean" class="package.UserSessionBean"/>
<jsp:getProperty name="userSessionBean" property="email"/>
Run Code Online (Sandbox Code Playgroud)

当我将相同的bean注入到我从API中的另一个servlet调用的服务中时,会出现问题.在这种情况下,我没有在JSP页面获得更新值.看起来我在JSP页面和使用@Inject注释的服务内部获得了不同的bean

任何人都可以建议如何在JSP和从servlet访问的服务层中使用相同的SessionScoped bean?

jsp servlets usebean cdi

1
推荐指数
1
解决办法
724
查看次数