Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

jsf 2 - How to save an object into JSF Session

I try to save the object into sessionmap but it is giving me an exception

public class testclass {

public static void main(String[] args) throws IOException
{
   UserInfo ui = new UserInfo();
   UserLogin ul= new UserLogin();

   ui.setAdds("India");
   ui.setEId("[email protected]");
   ui.setFName("someone");
   ui.setLName("someone2");
   ui.setStatus("single");
   ul.setPswd("somename");
   ul.setUserId("121");
   ul.setUserinfo(ui);



   AnnotationConfiguration config = new AnnotationConfiguration();
   config.configure("hibernate.cfg.xml");
   //new  SchemaExport(config).create(true, true);
   SessionFactory factory = config.buildSessionFactory();
   Session session = factory.getCurrentSession();
   System.out.println("Session configured");
   session.beginTransaction();
   session.save(ul);
   System.out.println("object saved");
   Query q = session.createQuery("from UserLogin where UserId='121'");
   UserLogin user = (UserLogin)q.uniqueResult();

   if(user!=null)
   {

      ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
      Map<String, Object> sessionMap = externalContext.getSessionMap();
      sessionMap.put("User",user);
      UserLogin hd =  (UserLogin)sessionMap.get("User");
      System.out.println("the user id is "+hd.getUserId());  
    }
        session.getTransaction().commit();

}

Exception:

Exception in thread "main" java.lang.NullPointerException at BeanMngr.testclass.main(testclass.java:58) Java Result: 1 BUILD SUCCESSFUL (total time: 4 seconds)

How is this problem caused and how can I solve it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to store an object in jsf session do the following:

FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("yourKey", yourObject);

The SessionMap is a Map<String, Object> and you can access your stored objects with the help of the get(Object key) method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...