从 GlassFish 4.1 中的自定义 JNDI 资源返回值

Returning a value from a custom JNDI resource in GlassFish 4.1

我已经尝试过多种方式来实现,但这是对我来说最有意义的方式,而且我仍然无法 return 从我的资源中获取任何东西。我使用 GlassFish 管理 GUI 添加了资源(本质上,我试图在本地服务器上保存用户名和密码)。

虽然我收到空指针异常 (NPE),但请不要将我指向此处,这对我一点帮助都没有。 What is a NullPointerException, and how do I fix it?

这是我的支持 classes...

正在创建 bean

   @LocalBean
   @Stateless

public class JndiProperties {

    @Resource(name="jndiCreds")
    private Properties properties;

    public String getUser() {
        return properties.getProperty("UserName");
    }
    public String getPass() {
        return properties.getProperty("UserPass");
    }
}

这是我的 bean 管理器:

 @ManagedBean
 @ViewScoped
    public class GetCreds {
        @Inject
        private JndiProperties property;
        public String getUserName(){
            return property.getUser();
        }
        public String getPassword(){
            return property.getPass();
        }
    }

这就是我对他们的称呼

GetCreds creds = new GetCreds();
String username = creds.getUserName();
String pass =  creds.getPassword();

我将资源命名为 jndiCreds,名称为 UserName 和 UserPass,其值包含各自的数据。

这是 GlassFish GUI 的视图:

知道为什么它不会 return 我请求的信息吗?当我从 getCreds 调用任一函数时尝试调用资源时,我收到 NPE。

帮助将不胜感激;我很卡。

我决定不再尝试使用 bean 而是直接访问它(尽管我在这里放弃了一些安全性)。我正在尝试以上下文方式访问数据。但!我还是做不到!这是我的新支持 class:

public class JndiProperties {

    public Properties getProperties(String jndiName) {
        Properties properties = null;
        try {
            InitialContext context = new InitialContext();
            properties = (Properties) context.lookup(jndiName);
            context.close();
        }
        catch (NamingException e) {

            return null;
        }
        return properties;
    }

这就是我获取信息的方式:

JndiProperties creds = new JndiProperties();

String username = creds.getProperties("jndiCreds").getProperty("UserName");
String pass =  creds.getProperties("jndiCreds").getProperty("UserPass");

String credentials = String.join(System.getProperty("line.separator"),
                                 "user=" + username,
                                 "password=" + pass);
System.out.print(credentials);

我正在使用上面显示的相同资源。我仍然以空指针结束......任何帮助都会大大 appreciated.Feel 免费回答我的 bean 实现有什么问题。

我想通了!

首先发生的事情是,我是个彻头彻尾的白痴,我试图用 JUnit 测试我的程序(它不 运行 在服务器上!)

由于程序未在 GlassFish 上 运行,因此无法访问资源。

其次,(也是最重要的)我缺少应用程序服务器-rt.jar-非常重要。