我尝试将对象保存到sessionmap中,但它给了我一个异常
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 BUILD SUCCESSFUL(总时间:4秒)
这个问题是如何引起的?如何解决?
答案 0 :(得分:9)
如果要在jsf会话中存储对象,请执行以下操作:
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("yourKey", yourObject);
SessionMap是Map<String, Object>
,您可以借助get(Object key)
方法访问存储的对象。