如何将对象保存到JSF Session中 [英] How to save an object into JSF Session

查看:177
本文介绍了如何将对象保存到JSF Session中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将对象保存到sessionmap中,但这给了我一个例外

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();

}

例外:

BeanMngr.testclass.main(testclass.java:58)上的线程"main"中的java.lang.NullPointerException异常Java结果:1构建成功(总时间:4秒)

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?

推荐答案

如果要将对象存储在jsf会话中,请执行以下操作:

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

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

SessionMap是一个Map<String, Object>,您可以在get(Object key)方法的帮助下访问存储的对象.

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

这篇关于如何将对象保存到JSF Session中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆