我正在使用会话范围的托管 bean 来处理 Java EE 应用程序中的登录。在我对用户进行身份验证后,用户对象将保存在此会话 bean 中。但是,刷新页面后,会话 bean 值消失了。
我正在调试代码,结果是在页面刷新时再次调用会话范围托管 bean 的构造函数,因此用新用户初始化用户对象。我想这不是正常行为,因为它应该保留在会话中,不是吗?
我发布了登录托管 bean 的某些部分,包括参数和登录方法。基本上enteredEmail 和enteredPassword 代表登录表单上输入的数据。如果身份验证成功,loggedIn 布尔值将变为 true,并且登录的用户对象存储在 checkedUser 变量中。
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class LoginController implements Serializable {
@EJB
private LoginSessionBean loginSessionBean;
@EJB
private LecturerFacade lecturerFacade;
private Lecturer checkedUser;
private String enteredEmail;
private String enteredPassword;
private boolean loggedIn;
/** Creates a new instance of loginController */
public LoginController() {
loggedIn = false;
checkedUser = new Lecturer();
}
public String login(){
RequestContext context = RequestContext.getCurrentInstance();
FacesMessage msg = null;
this.setCheckedUser(lecturerFacade.findLecturerByEmail(enteredEmail));
if(loginSessionBean.checkPassword(checkedUser, enteredPassword))
{
loggedIn = true;
msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", checkedUser.getFirstName()+ " " + checkedUser.getLastName());
FacesContext.getCurrentInstance().addMessage(null, msg);
context.addCallbackParam("loggedIn", loggedIn);
}
return "Index";
我还发布了上述托管 bean 使用的两个 EJB。LecturerFacade 使用输入的电子邮件检索用户对象,而 loginSessionBean 检查密码。
@Stateless
public class LecturerFacade extends AbstractFacade<Lecturer> {
@PersistenceContext(unitName = "EffectinetWebPU")
private EntityManager em;
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;
protected EntityManager getEntityManager() {
return em;
}
public LecturerFacade() {
super(Lecturer.class);
}
public Lecturer findLecturerByEmail(String email) {
try {
return (Lecturer) this.getEntityManager().createQuery("SELECT l FROM Lecturer l WHERE l.email = :email").setParameter("email", email).getSingleResult();
} catch (NoResultException e) {
System.err.println("Caught NOResultException: "+ e.getMessage());
return null;
} catch (NonUniqueResultException e) {
System.err.println("Caught NonUniqueResultException: "+ e.getMessage());
return null;
} catch (IllegalStateException e) {
System.err.println("Caught IllegalStateException: "+ e.getMessage());
return null;
}
}
_
@Stateless
public class LoginSessionBean {
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
@PersistenceContext(unitName = "EffectinetWebPU")
private EntityManager em;
protected EntityManager getEntityManager() {
return em;
}
public void setEntityManager(EntityManager em) {
this.em = em;
}
public boolean checkPassword(Lecturer user, final String enteredPassword) {
if (user.getPassword().equals(enteredPassword)) {
return true;
} else {
return false;
}
}
}
如果有人对出了什么问题有任何建议,请告诉我
我使用 glassfish 3.1 作为应用程序服务器和 Primefaces 作为 JSF 库。另外,我已经检查并从正确的包中导入了 sessionScoped 注释,而不是从 javax.enterprise ...