如何在会话中存储检索到的对象并访问后记?

编程入门 行业动态 更新时间:2024-10-27 05:21:09
本文介绍了如何在会话中存储检索到的对象并访问后记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试创建一个简单的登录页面.我使用休眠从数据库中检索User对象.该部分工作正常,我正在这样做,如下所示:

I am trying to create a simple login page. I retrieve a User object from my database using hibernate. That part works fine, I'm doing that as follows:

//data from login form String username = request.getParameter("username").trim(); String password = request.getParameter("password").trim(); SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); try { User currentUser = (User) session.get(User.class, username); if(password.equals(currentUser.getPassword())) { response.sendRedirect("index.jsp?page=login&success=true"); } else { session.getTransaction().rollback(); response.sendRedirect("index.jsp?page=login&success=false"); } } catch //...

给出正确的凭据,登录成功.如果我理解正确,那么上面的代码已经将用户存储在了会话中,如果登录成功,那么我要做的就是访问会话?

Given the correct credentials, login is successful. If I understand correctly, my code above already stores the User in the session, if the login was successful, so all I have to do is access the session?

但是,我无法弄清楚如何从我网站其他位置的会话中访问检索到的User对象.用户登录后,我想在我的网站上显示特定于用户的信息,为此,我需要检查用户名以及该用户是否已登录.

However I can't figure out how to access the retrieved User object from the session in other places of my website. After the user is logged in, I want to show user-specific information on my website and for that, I need to check the username and whether the user is logged in at all.

总结一下:如何在网站的其他部分使用检索到的User对象?

So to sum up: How can I use the retrieved User object in other parts of my website?

我刚刚开始学习Java EE并进入休眠状态,所以请多多包涵.

I just started learning Java EE and hibernate, so please bear with me.

推荐答案

您可以使用HttpSession来实现,该会话可以由HttpServletRequest对象检索.

You can do it using an HttpSession that can be retrieved by the HttpServletRequest object.

HttpSession httpSession = request.getSession(); httpSession.setAttribute("user", user);

现在要检查用户对象是否存在于应用程序的不同部分中,您可以执行以下操作:

Now to check if the user object is present in different parts of your application, you can do the following:

HttpSession httpSession = request.getSession(false); //False because we do not want it to create a new session if it does not exist. User user = null; if(httpSession != null){ user = (User) httpSession.getAttribute("user"); } if(user!=null){ // Do stuff here }

要注销用户或换句话说,要使会话无效,可以调用invalidate方法.

To logout a user or in other words, to invalidate the session, you can call the invalidate method.

httpSession.invalidate();

有用的链接: HttpServletRequest 和 HttpSession

更多推荐

如何在会话中存储检索到的对象并访问后记?

本文发布于:2023-10-29 20:29:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1540662.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:后记   对象   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!