本文介绍了Servlet上下文范围与全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ServletContext中存储变量与将其作为其中一个类的公共静态成员之间的区别是什么(如果有的话)?

What (if any) is the difference between storing a variable in the ServletContext and just having it as a public static member of one of the classes?

而不是写作:

// simplified (!)
int counter = (Integer)getServletContext().getAttribute("counter");
counter++;
this.getServletContext().setAttribute("counter", counter);

为什么不只是:

// in class MyServlet
public static int counter = 0;

// in a method somewhere
MyServlet.counter++;

(请忽略并发问题,这只是一个愚蠢的例子)

(Ignore concurrency issues, please, this is just a dumb example)

据我所知,这两个选项在Tomcat下的行为方式相同。使用第一个选项有什么好处吗?

From what I can tell, these two options behave the same way under Tomcat. Is there something better about using the first option?

推荐答案

Web容器知道你的servlet上下文,但不知道你的静态变量其中是您的类加载器的私有内容。

The web container knows about your servlet context, but not about your static variables which as skaffman says are private to your classloader.

导致两个不同请求由不同类加载器中的应用程序实例(可能是服务器重启,Web应用程序重新部署或多节点服务器)提供服务的任何内容都将打破你的逻辑。当Web容器知道它并且可以序列化它或拥有一个公共存储库时,servlet上下文将在这些东西中存活下来。

Anything that cause two different requests to be served by an application instance in a different classloader (this could be server restarting, web application redeployment, or multi-node servers) will case your logic to break. The servlet context will survive these things as the web container knows about it and can serialize it or have a common repository.

这篇关于Servlet上下文范围与全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 20:25