我正在学习Java 6 EE,我有一个简单的网络应用程序。
我有UserBean
类使用CurrencyManager
类。 CurrencyManager
是应用程序作用域,是托管bean。 UserBean
是托管bean和会话作用域。
这是我的UserBean
:
@ManagedBean
@SessionScoped
public class UserBean implements Serializable{
private String username;
private ArrayList<Money> ownedMoney;
private CurrencyManager currencyManager;
private BigDecimal credits;
public UserBean() {
currencyManager = new CurrencyManager();
username = "User";
ownedMoney = new ArrayList<>();
ownedMoney.add(new Money(new BigDecimal(15000), currencyManager.getCurrency("CZK")));
ownedMoney.add(new Money(new BigDecimal(100), currencyManager.getCurrency("USD")));
credits = new BigDecimal(150);
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public BigDecimal getCredits() {
return credits;
}
public void setCredits(BigDecimal credits) {
this.credits = credits;
}
public ArrayList<Money> getOwnedMoney() {
return ownedMoney;
}
public void setOwnedMoney(ArrayList<Money> ownedMoney) {
this.ownedMoney = ownedMoney;
}
public CurrencyManager getCurrencyManager() {
return currencyManager;
}
public void setCurrencyManager(CurrencyManager currencyManager) {
this.currencyManager = currencyManager;
}
}
这是我的CurrencyManager
:
@ManagedBean(name = "currencyManager")
@ApplicationScoped
public class CurrencyManager {
private HashMap<String, Currency> currencies;
public CurrencyManager() {
this.currencies = new HashMap<>();
currencies.put("CZK", new Currency("CZK", new BigDecimal("0.0503")));
currencies.put("GBP", new Currency("GBP", new BigDecimal("0.59")));
currencies.put("EUR", new Currency("EUR", new BigDecimal("1.38")));
currencies.put("USD", new Currency("USD", new BigDecimal("1.0")));
}
public Currency getCurrency(String name){
return currencies.get(name);
}
public java.util.Collection<Currency> getCurrencies() {
return currencies.values();
}
public void setCurrencies(HashMap<String, Currency> currencies) {
this.currencies = currencies;
}
}
我发布的代码工作正常。但是,我不想在CurrencyManager
课程中实例化UserBean
- 这就是为什么我将其设为ApplicationScoped,因为它应始终可用。
如果我删除实例化(UserBean
构造函数中的第一行)并将声明更改为:
@ManagedProperty(value = "#{currencyManager}")
private CurrencyManager currencyManager;
然后查询ownedMoney
中UserBean
属性的第一个页面引发javax.servlet.ServletException: Cant instantiate class: model.UserBean.
,其根本原因为NullPointerException
。 GlassFish日志显示NullPtr出现在UserBean
构造函数中,当我在getCurrency
上调用currencyManager
时,此处:
ownedMoney.add(new Money(new BigDecimal(15000), currencyManager.getCurrency("CZK")));
你能告诉我我做错了什么吗?
答案 0 :(得分:0)
我刚刚遇到同样的问题,并且偶然发现它不起作用,如果我尝试使用firefox(实际上是linux下的icedove),但是如果我尝试使用eclipse内置浏览器,那么工作正常。
即便如此,这对我来说没有意义,您是否尝试过不同的浏览器?