Global variable on servlet. is global for all sessions, or only for the current session? [duplicate]

守給你的承諾、 提交于 2020-02-03 09:18:04

问题


I need to share information while the applicaiton is running; if I have:

public class example extends HttpServlet
{
    Object globalObject;

    doGet...
    doPost....
}

A user is using the aplication through server and the object globalObject; if another user use the application, will share the object with the first user?


回答1:


A user is using the aplication through server and the object globalObject; if another user use the application, will share the object with the first user?

Yes! Different threads might be used to render request for different users but the same servlet instance is used.So yes the variable will be common to all requests. In-fact this is why it is said we should not have global variables to ensure thread safety.




回答2:


with HttpSession your variable will be related to each users session, not the application itself

you can do this as follow

ServletContext application = getServletConfig().getServletContext();  

String data = "test";  
application.setAttribute("variable", data);  

String data_rtrvd= (String) application.getAttribute("variable"); 

Is JSP code you can do:

<jsp:useBean id="obj" class="my.package.name.MyClass" scope="application" />



回答3:


The same instance of the variable will be used by all requests handled by the servlet. Servlets are not thread safe since only one instance of the servlet is created.

This will cause two users to use the same instance of globalObject.




回答4:


That depends on how your application server allocates servlets.

If your application server allocates only one servlet instance, then yes, all requests will share access to the global variable and you must account for that in your design (unless you choose to implement the deprecated SingleThreadModel interface, which will guarantee that, while all requests will have access to the global variable, they won't access it concurrently. Don't do it. Find another way).

If your application server allocates more than one servlet instance, then the answer is "not necessarily".

Obviously, you are often masked from the server's decisions (as to whether to instantiate multiple instances or not), so you must design for safety.




回答5:


Generally speaking, threads are singletons, so the answer to your question is yes. However, if you want to share data between different users, you should use a true Singleton implementation. Also consider concurrency, because you'll surely have many threads executing at the same time (One for each request that is received by the server)



来源:https://stackoverflow.com/questions/24469257/global-variable-on-servlet-is-global-for-all-sessions-or-only-for-the-current

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!