Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k 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("someone@yahoo.com");
   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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...