如何在应用程序一开始就将变量保存到 session 中? 当我第一次运行应用程序时,下面的代码没有执行。
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
session.setAttribute("flag", true);
//etc...
}
最佳答案
该代码不会在服务器启动时执行,因为此时没有请求,因此也没有 session 。这个方法属于一个 servlet,一旦某个客户端点击映射到它的 url 就会调用它。
如果您需要在应用程序启动时执行某些操作,请使用 ServletContextListener。如果您必须在您的 webapp 中存储一些变量以供“全局”使用,请使用 ServletContext。如果您真的必须将它存储到 session 中,请使用 HttpSessionListener。
关于java - 应用程序启动时保存到 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33690789/