简体   繁体   中英

Is there a way to have a “universal variable” in Java Web?

Is there a way to have a variable that affects all sessions and all users in Java Web, Java Servlets and JSP?

I know you can have these variables in the database but is there an other way to achive this?

I think servlet context will do the job.

For example:

ServletContextListener

public void contextInitialized(final ServletContextEvent arg0) {
        arg0.getServletContext().setAttribute("my_var", 0);
        ...
}

HttpServlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int myVar = (Integer) getServletContext().getAttribute("my_var");
        ...
}

Declare public class then add static variables.

public class Globals {
   public static int globalVariable = 0;
}

then Globals.globalVariable will be accessible anywhere within application.

You can achieve in many ways:

  • Use a config file

    Maybe you can use config file, for example, there is a config.properties, which has level = 10 , you load it in a Listener when web server start, and store in memory via a Map, and you can change/access it any time, you can send the value via json to front-end too.

  • Use Application scope variable in jsp/servlet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM