Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a Variable at Application Scope so it shared among Sessions

I am using Struts2 with Spring plugin. I want to set a variable value which will be shared among all the different sessions. It will just be one string value but if one session changes it I want the changed value to be available to all the sessions.

What will be the best way to do this? Code Example will be great.

like image 282
anon Avatar asked Jan 20 '26 13:01

anon


2 Answers

http://docs.oracle.com/cd/E17802_01/products/products/servlet/2.3/javadoc/javax/servlet/ServletContext.html

In the Servlet code:

Object attr = getServletContext().getAttribute("ATTR_NAME");
// Do something with it and...

getServletContext().setAttribute("ATTR_NAME", attr);

This is the generic Java EE Servlet way ;)

like image 56
ITCuties Avatar answered Jan 23 '26 02:01

ITCuties


You can do something like this using Spring

package mypackage;  

import javax.servlet.ServletContext;  
import org.springframework.web.context.ServletContextAware;  

public class MYDataLoader implements ServletContextAware {  

    public void setServletContext(ServletContext servletContext) {  
        servletContext.setAttribute("myKey", value);  
    }  
} 

In rest of code you just get the servletContext object from request->session and get the value of "mykey".

like image 23
Manoj Kathiriya Avatar answered Jan 23 '26 04:01

Manoj Kathiriya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!