Search code examples
javaservletsjettyembedded-jettyjetty-9

Programmatically adding HttpSessionListener to Jetty not working


I am using Jetty 9 embedded and try to use ServletContext.addListener(T) to add a HttpSessionListener from within my Servlet.init() method. However, the methods on my session listener don't ever get called. At the same time, when I let my listener class implement ServletRequestListener, the request listener related methods get called. I do call getSession(), so session creation should be triggered.

Any Ideas, workarounds? Am I misreading the spec? Known issue?


Solution

  • ServletContext.addListener() is only supported (per spec) in a narrow scope.

    It can be used from one of the 2 code paths.

    1. ServletContainerInitializer.onStartup(Set<Class<?>> c, ServletContext ctx)
    2. ServletContextListener.contextInitialized(ServletContextEvent sce)

    All other uses of ServletContext.addListener() are invalid.