Servlet 上下文和单例对象
我见过一个 Singleton 类对象的示例,其中有一个包含从数据库检索的用户 ID 和密码的映射。这将有助于在用户登录期间避免每次都访问数据库。
现在我在想,这不能通过ServletContext属性来完成吗?
基本上,在这两种情况下,我们都会有应用程序范围的对象。
那么,在这种情况下我们可以使用 ServletContext 属性吗?
I have seen an example of Singleton class object where it has a map containing user-id and password retrieved from database. This will help not to hit DB everytime during user login.
Now i am thinking, can't this be done through ServletContext attribute.
Basically on both the cases we will have application wide object.
So, Can we use ServletContext attribute in this case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您需要从应用程序中的任何位置访问
Map
,那么它实际上是放置它的最佳位置。您可以注册 Servlet Context Listener 并在
contextInitialized
您可以获取一个单例并将其存储为ServletContext
的属性,然后通过获取相应的属性在 Web 应用程序中的任何位置访问它
getServletContext().getAttribute("UsersMap");
If you need to access the
Map
from anywhere in your application then yes it is actually the best place to place it.You can register a Servlet Context Listener and on
contextInitialized
you can get a singleton and store it as an attribute ofServletContext
Then access it using by anywhere in your web application by getting the corresponding attribute
getServletContext().getAttribute("UsersMap");
如果数据库中的数据基本上是静态的,那么是的,你可以这样做。如果数据库中的数据是动态的,那么不,不建议这样做。否则,您需要编写相当多的代码来保持数据库和 servletcontext 变量同步。当新用户在网络应用程序上注册时,您当然希望该用户能够登录。
无论如何,如果数据库中有 100 万用户怎么办?您真的想将这一切复制到服务器内存中吗?出于什么目的?这完全违背了数据库的目的。您想验证登录吗?我真的无法想象为什么验证登录会如此昂贵,以至于您需要在服务器内存中拥有整个数据库的副本。这是一个像样的数据库可以在不到一毫秒的时间内完成的工作。问题的原因肯定必须从其他地方解决。
也许您不必要地将整个数据库复制到 Java 内存中,并在 Java 中按行完全进行验证,而不是利用 SQL
WHERE
子句?像这样的东西吗?对于刚刚接触数据库且不了解 SQL 强大功能的初学者来说,这是一个经常出现的思维错误。如果您在用户名列上设置
UNIQUE
索引,并为密码列建立索引,则以下方式会更高效:If the data in the DB is basically static, then yes, you could do so. If the data in the DB is dynamic, then no, this is not recommended. You'd otherwise need to write quite some code to keep the DB and the servletcontext variable in sync. When a new user registers on the webapp you of course want this user to be able to login.
Regardless, what if you have 1 million users in DB? Would you really want to copy this all into server's memory? For what purposes? This completely defeats the purpose of the DB. Do you want to validate a login? I really can't imagine why validating a login would be that expensive that you need to have a copy of the entire DB in server's memory. This is a job which a bit decent DB can do in less than a millisecond. The cause of the problem must definitely be solved elsewhere.
Perhaps you're unnecessarily copying the entire DB into Java's memory and doing the validation fully in Java on a per-row basis instead of utilizing the SQL
WHERE
clause? Something like this?This is a very often recurring thinking mistake among beginners who are new to databases and not understanding the powers of SQL. If you set an
UNIQUE
index on the username column and index the password column as well, the following is way much more efficient: