我将 JSF 2 和 GlassFish Server 4 与 CDI 一起使用(导入 javax.enterprise.context ...)。我正在尝试将 SessionBean A 注入另一个 SessionBean B,但是当我尝试在第二个 http 请求上访问 B 时,它不再存在。而是创建了一个 B 的新实例。因此,任何 bean 中都没有信息。这是我的一些代码:
Bean A:(这个 bean 保存了所有的登录信息)
@Named("login")
@SessionScoped
public class LoginBean implements Serializable {
private Farmer aFarmer;
private Admin anAdmin;
private User loginInfo;
private int tries;
private boolean loggedIn;
private int accessLvl;
/**
* Constructor for a LoginBean, setting default values
*/
public LoginBean() {
}
@PostConstruct
public void init() {
loginInfo = new User();
tries = 0;
loggedIn = false;
}
Bean B:(此 bean 保存所有农民信息,用于对农民采取行动)
@Named("farmer")
@SessionScoped
public class FarmerController implements Serializable{
private @Inject LoginBean login;
private Farmer theFarmer;
private ArrayList<Integer> dates;
private ArrayList<Integer> months;
private ArrayList<Integer> years;
private int date; //date place holder
private int month; //month place holder
private int year; //year place holder
private String response; //confirmation response
private String confPwd;
private String oldPwd;
private String email;
private String password;
/**
* Default constructor for FarmerController, sets standard calendar values
*/
public FarmerController() {
}
@PostConstruct
public void init() {
theFarmer = new Farmer();
//standard values for dates
dates = new ArrayList<>();
for (int i = 0; i < 31; i++) {
dates.add(i+1);
}
//standard values for months
months = new ArrayList<>();
for (int i = 0; i < 12; i++) {
months.add(i+1);
}
//standard values for year, current year - 100
Calendar cal = new GregorianCalendar();
int tempyear = cal.get(Calendar.YEAR);
years = new ArrayList<>();
for (int i = 0, j = tempyear; i < 100 && j > tempyear - 100; i++, j--) {
years.add(j);
}
//check when bean is constructed
System.out.println("FarmerController constructed");
}
index.xhtml :(这是我登录的地方,效果很好)
<h:form class="form-horizontal form-group">
<fieldset>
<div class="input-group">
<h:inputText id="username" class="form-control" p:placeholder="Brukernavn/Email" value="#{farmer.email}"/>
</div>
<div class="input-group">
<h:inputSecret id="password" class="form-control" p:placeholder="Passord" value="#{farmer.password}"/>
</div>
<div class="input-group">
<h:commandButton id="signin" value="Logg inn" class="btn btn-success" action="#{farmer.login()}"/>
</div>
</fieldset>
</h:form>
登录后,我进入第二个 .xhtml 页面,所有内容都正确显示。但是,当我进一步导航到另一个引用此 FarmerController 的页面时,它会创建一个新 bean,该 bean 没有任何登录信息。为什么会发生这种情况?我究竟做错了什么?
更新:我也尝试过合并两个 bean(所有操作只使用 1 个),我也有同样的问题,即登录后 SessionScoped bean 被破坏。