How do I get and set an object in session scope in JSF?

前端 未结 3 1769
情书的邮戳
情书的邮戳 2020-12-07 16:18

I need to persist just one object in session scope of my JSF application. Where do I define a session variable, and how do I get and set it from either a view file or backin

3条回答
  •  庸人自扰
    2020-12-07 16:26

    When you call the method FacesContext.getCurrentInstance() it will return the current thread but in case of P.S.V.M there will be no thread running in application context. So you get a NPE.

    Better use something like this:

    public String checker() {
        SessionFactory factory = HibernateUtil.getSessionFactory();
        Session session = factory.getCurrentSession();
        session.beginTransaction();
        Query q = session.createQuery("from UserLogin where UserId='"
                + uid.getUserId() + "'and Pswd='" + uid.getPswd()
                + "'and RoleId='" + uid.getRoleId() + "'");
        setUid((UserLogin) q.uniqueResult());
    
        System.out.println("upto here every thing is workind properly");
    
        if (uid != null) {
            FacesContext context = FacesContext.getCurrentInstance();
    
            HttpServletRequestrequest = (HttpServletRequest) context
                    .getExternalContext().getRequest();
            HttpSession appsession = request.getSession(true);
    
            if (appsession.isNew() == false) {
                appsession.invalidate();
                appsession = request.getSession(true);
            }
            context.getExternalContext().getSessionMap().put("userbean", uid);
            session.close();
            return uid.getRoleId();
        } else
            return "invalid";
    }
    

    and put it into a session bean. You can use the code to validate users.

提交回复
热议问题