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?
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
.
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" />
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With