HttpSessionListener.sessionCreated() not being cal

2019-02-20 03:56发布

I have a very simple Servlet and a very simple 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)  { 
    }

}

My HttpSessionListener.sessionCreated() method is never called (no log output), and I end up getting a NullPointerException on the line where I'm calling getSession()

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

I tried calling getSession() without true as well, but same problem.

I don't get it - isn't the @WebListener annotation enough to invoke my listener? Eclipse even displays it as a listener under Deployment Descriptor/Listeners.

2条回答
狗以群分
2楼-- · 2019-02-20 04:12

Turns out it was one of those stupid Eclipse issues...

Project->Clean... and restarting Tomcat did the trick.

查看更多
对你真心纯属浪费
3楼-- · 2019-02-20 04:37

If you're not using @WebListener make sure your listeners are referenced in the 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.

查看更多
登录 后发表回答