java Servlet 上下文范围与全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1184556/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:31:45  来源:igfitidea点击:

Servlet context scope vs global variable

javatomcatservlets

提问by itsadok

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?

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

Instead of writing:

而不是写:

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

Why not just have:

为什么不只有:

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

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

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

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

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

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

采纳答案by Thorbj?rn Ravn Andersen

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

Web 容器知道您的 servlet 上下文,但不知道您的静态变量,正如skaffman 所说,这些变量对您的类加载器来说是私有的。

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.

任何导致两个不同请求由不同类加载器中的应用程序实例(这可能是服务器重新启动、Web 应用程序重新部署或多节点服务器)提供服务的情况都会导致您的逻辑中断。servlet 上下文将在这些事情中幸存下来,因为 Web 容器知道它并且可以对其进行序列化或拥有一个公共存储库。

回答by skaffman

Well they're not quite the same; servlet-context-scope is private to the webapp, whereas static scope is private to the classloader. Depending on your container and how it's configured, these may or may not be the same. When thinking in terms of webapps and JavaEE, using a context-coped field is going to be more reliably portable. Also, context-scoped attributes are easier to access from JSPs, i.e. you don't need scriptlets to get to them.

好吧,它们并不完全相同;servlet-context-scope 是 webapp 私有的,而 static 范围是 classloader 私有的。根据您的容器及其配置方式,这些可能相同也可能不同。在考虑 webapps 和 JavaEE 时,使用上下文处理的字段会更可靠地移植。此外,上下文范围的属性更容易从 JSP 访问,即您不需要脚本来访问它们。