如何在会话中存储检索到的对象并访问后记? [英] How to store retrieved object in session and access it afterwords?

查看:80
本文介绍了如何在会话中存储检索到的对象并访问后记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的登录页面.我使用休眠从数据库中检索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

这篇关于如何在会话中存储检索到的对象并访问后记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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