java 如何在会话中存储检索到的对象并在后记中访问它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33481815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store retrieved object in session and access it afterwords?
提问by ksbg
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:
我正在尝试创建一个简单的登录页面。我User
使用休眠从我的数据库中检索一个对象。这部分工作正常,我这样做如下:
//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?
给定正确的凭据,登录成功。如果我理解正确,我上面的代码已经将用户存储在会话中,如果登录成功,那么我所要做的就是访问会话?
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?
总结一下:如何User
在网站的其他部分使用检索到的对象?
I just started learning Java EE and hibernate, so please bear with me.
我刚开始学习 Java EE 和 hibernate,所以请耐心等待。
回答by Harsh Poddar
You can do it using an HttpSession that can be retrieved by the HttpServletRequest object.
您可以使用可由 HttpServletRequest 对象检索的 HttpSession 来完成此操作。
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
}
To logout a user or in other words, to invalidate the session, you can call the invalidate method.
要注销用户或换句话说,要使会话无效,您可以调用 invalidate 方法。
httpSession.invalidate();
Useful links: HttpServletRequestand HttpSession
回答by Nathan Hughes
HttpSession is different from the Hibernate session. The Hibernate session provides a way for you to query and save persistent entities that are stored in a database. The HttpSession is provided by the servlet container to give a way to store objects for a given user based on a cookie provided in the user's request.
HttpSession 不同于 Hibernate 会话。Hibernate 会话为您提供了一种查询和保存存储在数据库中的持久实体的方法。HttpSession 由 servlet 容器提供,以根据用户请求中提供的 cookie 为给定用户提供一种存储对象的方法。
What you store in the HttpSession should be minimal, partly to save on overhead from nodes in the cluster reconciling their sessions but mostly to make your application less error-prone. Here it could be sufficient to store a user's ID in the session rather than the whole user object. Even if the User object contained roles it would be better to look those up for each request so that any changes get applied immediately. Also by storing only ids you avoid problems with reattaching entities (allowing you to avoid one of the more confusing and troublesome parts of using Hibernate). When something else in your application needs to access the User it can query the Hibernate session (using session.get(id)
) passing in the primary key value stored in the HttpSession.
您在 HttpSession 中存储的内容应该最少,部分是为了节省集群中节点协调会话的开销,但主要是为了使您的应用程序不易出错。在这里,在会话中存储用户 ID 而不是整个用户对象就足够了。即使 User 对象包含角色,最好为每个请求查找这些角色,以便立即应用任何更改。此外,通过仅存储 id,您可以避免重新附加实体的问题(允许您避免使用 Hibernate 时更令人困惑和麻烦的部分之一)。当应用程序中的其他内容需要访问 User 时,它可以查询 Hibernate 会话(使用session.get(id)
),并传入存储在 HttpSession 中的主键值。
You should use a 1-way hash to store passwords so that will change how you compare passwords.
您应该使用单向哈希来存储密码,以便更改您比较密码的方式。
The application should create a Hibernate SessionFactory once only upon initialization, it is threadsafe and everything in the application should use that one instance.
应用程序应该只在初始化时创建一个 Hibernate SessionFactory,它是线程安全的,应用程序中的一切都应该使用那个实例。
Rolling back a transaction where all you do is select seems unnecessary.
回滚您所做的只是选择的事务似乎没有必要。
Typically you access the HttpSession only from the view and the web controller. It looks like you have web controller logic and business logic lumped together, a division of responsibilities between controller and servicemay be helpful here.
通常,您只能从视图和 Web 控制器访问 HttpSession。看起来您将 Web 控制器逻辑和业务逻辑混为一谈,控制器和服务之间的职责划分在这里可能会有所帮助。
回答by Madushan Perera
The Session you have mentioned here(org.hibernate.Session) is cannot access from the other places of your web site instead you put your User object into a HttpSession.
您在此处提到的 Session(org.hibernate.Session) 无法从您网站的其他地方访问,而是将您的 User 对象放入HttpSession。
Here is how you going do this:
以下是您将如何执行此操作:
HttpSession httpSession = request.getSession();
httpSession.setAttribute("loggedUser", your_user_object reference_here );
Here is how you access from other placess:
以下是您从其他地方访问的方式:
httpSession.getAttribute("loggedUser");//return type is Object here
回答by x80486
Assuming you are in a Web application and you want something from the User
entity, you should propagate the same value/reference to the Web/controller layer (in case you are using an MVC approach); then keep it there since it's the most appropriate place to store something via the HTTP session provided by most frameworks.
假设你在一个 Web 应用程序中并且你想要从User
实体中得到一些东西,你应该将相同的值/引用传播到 Web/控制器层(如果你使用的是 MVC 方法);然后将其保留在那里,因为它是通过大多数框架提供的 HTTP 会话存储内容的最合适的位置。
RECOMMENDATION(S)
推荐(S)
- You should not be rolling back a get/select operation?
- A
SessionFactory
should be instantiated once.
- 您不应该回滚获取/选择操作吗?
- A
SessionFactory
应该被实例化一次。