设计问题-Webapp会话中的持久数据 [英] Design question - Persistent data in a webapp session

查看:79
本文介绍了设计问题-Webapp会话中的持久数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用servlet和jsps开发一个Web应用程序.我有一个关于存储在登录会话中需要在多个servlet中使用的数据的问题.例如,当用户登录时,我从数据库获取用户对象,并希望将其存储在某个地方,并让后续的servlet和jsps使用该对象,而不必再次查询数据库.我知道我必须将对象存储在全局数组中,但无法找出执行此操作的最佳方法.

I am developing a web app using servlets and jsps. I have a question about storing data I need to use across multiple servlets in a login session. When the user logs in, for example, I get the user object from the db and would like to store it somewhere and have the subsequent servlets and jsps use it without having to query the db again. I know that I have to store the object in a global array but am not able to figure out the best way to do this.

我正在考虑在webapp加载时创建静态哈希图或其他一些数据结构,并且可以使用它存储具有sessionID作为哈希图键的用户对象.

I am thinking of having a static hashmap or some other data structure created at webapp load time and I can use that to store the user object with the sessionID as the key for the hashmap.

有更好的方法吗?任何帮助表示赞赏.

Is there a better way? Any help is appreciated.

谢谢, -Vas

推荐答案

您不需要自己管理会话. servlet容器将透明地以 HttpSession .您通常使用 HttpServletRequest#getSession() 获取对HttpSession的引用.

You don't need to manage the sessions yourself. The servletcontainer will do it for you transparently in flavor of HttpSession. You normally use HttpSession#setAttribute() to store an object in the session scope and HttpSession#getAttribute() to get an object from the session scope. You can use HttpServletRequest#getSession() to get hold of a reference to the HttpSession.

例如在登录servlet中:

E.g. in the login servlet:

User user = userDAO.find(username, password);
if (user != null) {
    request.getSession().setAttribute("user", user);
} else {
    // Show error?
}

您可以稍后在任何servlet中或在同一会话中的过滤器中将其取回

You can get it back later in any servlet or filter in the same session by

User user = (User) request.getSession().getAttribute("user");
if (user != null) {
    // User is logged in.
} else {
    // User is not logged in!
}

您甚至可以在JSP中通过EL来访问它:

You can even access it by EL in JSP:

<p>Welcome, ${user.username}!

(假设有一个Javabean getUsername()方法)

(assuming that there's a Javabean getUsername() method)

这篇关于设计问题-Webapp会话中的持久数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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