有没有办法让变量影响Java Web,Java Servlets和JSP中的所有会话和所有用户?
我知道你可以在数据库中拥有这些变量,但还有其他方法可以实现这个吗?
答案 0 :(得分:3)
我认为servlet上下文可以完成这项工作。
例如:
的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");
...
}
答案 1 :(得分:0)
声明公共类,然后添加静态变量。
public class Globals {
public static int globalVariable = 0;
}
然后Globals.globalVariable
可以在应用程序的任何位置访问。
答案 2 :(得分:0)
你可以通过多种方式实现:
使用配置文件
也许您可以使用配置文件,例如,有一个config.properties,它有level = 10
,您在Web服务器启动时将其加载到监听器中,并通过Map存储在内存中,您可以随时更改/访问它,您也可以通过json将值发送到前端。
在jsp / servlet中使用应用程序范围变量