Setting a Variable at Application Scope so it shar

2019-05-14 21:49发布

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.

2条回答
放荡不羁爱自由
2楼-- · 2019-05-14 22:29

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 ;)

查看更多
Bombasti
3楼-- · 2019-05-14 22:42

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".

查看更多
登录 后发表回答