应用程序启动时保存到会话
Save to session when the application starts
如何在应用程序一开始就将变量保存到会话中?
当我 运行 应用程序时,下面的代码没有执行..
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
session.setAttribute("flag", true);
//etc...
}
该代码不会在服务器启动时执行,因为此时没有请求,因此也没有会话。这个方法属于一个 servlet,一旦某个客户端点击映射到它的 url 就会调用它。
如果您需要在应用程序启动时执行某些操作,请使用 ServletContextListener。如果您必须存储一些变量以供 "global" 在您的 webapp 中使用,请使用 ServletContext。如果您真的必须将它存储到会话中,请使用 HttpSessionListener。
如何在应用程序一开始就将变量保存到会话中? 当我 运行 应用程序时,下面的代码没有执行..
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
session.setAttribute("flag", true);
//etc...
}
该代码不会在服务器启动时执行,因为此时没有请求,因此也没有会话。这个方法属于一个 servlet,一旦某个客户端点击映射到它的 url 就会调用它。
如果您需要在应用程序启动时执行某些操作,请使用 ServletContextListener。如果您必须存储一些变量以供 "global" 在您的 webapp 中使用,请使用 ServletContext。如果您真的必须将它存储到会话中,请使用 HttpSessionListener。