ksb*_*sbg 5 java hibernate jakarta-ee
我正在尝试创建一个简单的登录页面。我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 //...
Run Code Online (Sandbox Code Playgroud)
给定正确的凭据,登录成功。如果我理解正确,我上面的代码已经将用户存储在会话中,如果登录成功,那么我所要做的就是访问会话?
但是,我无法弄清楚如何User从我网站其他地方的会话中访问检索到的对象。用户登录后,我想在我的网站上显示特定于用户的信息,为此,我需要检查用户名以及用户是否完全登录。
总结一下:如何User在网站的其他部分使用检索到的对象?
我刚开始学习 Java EE 和 hibernate,所以请耐心等待。
您可以使用可由 HttpServletRequest 对象检索的 HttpSession 来实现。
HttpSession httpSession = request.getSession();
httpSession.setAttribute("user", user);
Run Code Online (Sandbox Code Playgroud)
现在要检查用户对象是否存在于应用程序的不同部分,您可以执行以下操作:
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
}
Run Code Online (Sandbox Code Playgroud)
要注销用户或换句话说,要使会话无效,您可以调用 invalidate 方法。
httpSession.invalidate();
Run Code Online (Sandbox Code Playgroud)
有用的链接:HttpServletRequest和HttpSession
| 归档时间: |
|
| 查看次数: |
18519 次 |
| 最近记录: |