gpt4 book ai didi

jsf-2 - 如何将对象保存到 JSF session 中

转载 作者:行者123 更新时间:2023-12-05 08:44:33 27 4
gpt4 key购买 nike

我尝试将对象保存到 session 映射中,但它给了我一个异常

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)

这个问题是怎么引起的,我该如何解决?

最佳答案

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

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

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

关于jsf-2 - 如何将对象保存到 JSF session 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7480325/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com