我试图实现这么多方法,但这是对我最有意义的方式,我仍然无法从我的资源中返回任何内容。我使用GlassFish管理GUI添加了资源(实质上,我试图在本地服务器上保存用户名和密码)。
虽然我得到一个空指针异常(NPE),但请不要指向我这里,它根本不能帮助我。 What is a NullPointerException, and how do I fix it?
以下是我的支持班......
创建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的视图:
知道为什么它不会返回我要求的信息吗?当我从getCreds调用函数时尝试调用资源时,我收到了NPE。
帮助将不胜感激;我很困惑。
我决定放弃尝试使用bean并直接访问它(虽然我在这里放弃了一些安全性)。我试图以上下文方式访问数据。但!我还是做不到!这是我的新支持课程:
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);
我使用的是上面显示的相同资源。我仍然以空指针结束......非常感谢任何帮助。也可以随意回答我的bean实现的错误。
答案 0 :(得分:0)
I have figured it out!
What was happening is first, I was a complete idiot, and I was trying to test my program with JUnit (IT DOES NOT RUN ON THE SERVER!)
Since the program wasn't being run on GlassFish, it couldn't access the resource.
Secondly, (and most importantly) I was missing the appserver-rt.jar- very important.