Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 251
user3550529 Avatar asked Jun 28 '14 17:06

user3550529


3 Answers

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.

like image 89
Aniket Thakur Avatar answered Oct 13 '22 00:10

Aniket Thakur


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" />
like image 24
Marcelo Bezerra bovino Avatar answered Oct 12 '22 23:10

Marcelo Bezerra bovino


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.

like image 34
Kevin Bowersox Avatar answered Oct 12 '22 23:10

Kevin Bowersox