java - HttpSessionListener.sessionCreated() 未被调用

标签 java servlets httpsession

我有一个非常简单的 Servlet 和一个非常简单的 HttpSessionListener:

@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
    private static final long serialVersionUID = 1L;


    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        getServletContext().setAttribute("applicationHits", new AtomicInteger(0));  
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("get");

        ((AtomicInteger) request.getServletContext().getAttribute("applicationHits")).incrementAndGet();
        ((AtomicInteger) request.getSession(true).getAttribute("sessionHits")).incrementAndGet();
        request.setAttribute("requestHits", 0);

        getServletContext().getRequestDispatcher("/view/HelloWorld.jsp").forward(request, response);
    }

}

@WebListener
public class SessionListener implements HttpSessionListener {

    public SessionListener() {
    }

    public void sessionCreated(HttpSessionEvent arg0)  {
        System.out.println("session listener");
        arg0.getSession().setAttribute("sessionHits", new AtomicInteger(0));
    }

    public void sessionDestroyed(HttpSessionEvent arg0)  { 
    }

}

我的 HttpSessionListener.sessionCreated() 方法从未被调用(没有日志输出),我最终在调用 getSession( )

((AtomicInteger) request.getSession(true).getAttribute("sessionHits")).incrementAndGet();
        request.setAttribute("requestHits", 0);

我也尝试在没有 true 的情况下调用 getSession(),但同样的问题。

我不明白 - @WebListener 注释是否足以调用我的监听器? Eclipse 甚至在 Deployment Descriptor/Listeners 下将其显示为监听器。

最佳答案

如果您不使用@WebListener,请确保在 web.xml 中引用了您的监听器。

<web-app>...
    <listener>
        <listener-class>com.yoursite.YourSessionListener</listener-class>
    </listener>

In order to receive these notification events, the implementation class must be either declared in the deployment descriptor of the web application, annotated with WebListener, or registered via one of the addListener methods defined on ServletContext.

关于java - HttpSessionListener.sessionCreated() 未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41082885/

相关文章:

java - 我的迭代器稍微关闭了......知道如何修复它吗?

java - 运行 spring 测试时加载类路径资源时出现 FileNotFoundException

java - 如何使我的网站与 servlet 通信?

python - 与网络应用程序建立 session 以进行爬网

java - 客户端上的 GWT HTTP session 可用性

java - tomcat服务器如何识别客户端以创建 session ID

java - 非法转义字符 "\"

java- 为什么我在使用 gui 创建 ATM 时收到 "class is not abstract and does not override abstract method"?

android 客户端中的 java.io.StreamCorrupted Exception`

javascript - 如何在 javascript、javaservlets、mysql 和 back 中使用 utf8?