I'm wiring up an embedded Jetty server in my main
and I want to enforce only cookies as a session tracking mode.
So I try to do:
//in main
ServletContextHandler contextHandler =
new ServletContextHandler(ServletContextHandler.SESSIONS);
contextHandler
.getServletContext()
.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE));
But I get the following:
Exception in thread "main" java.lang.IllegalStateException
at org.eclipse.jetty.servlet.ServletContextHandler$Context.setSessionTrackingModes(ServletContextHandler.java:1394)
My servlet context is not yet initialized.
The obvious solution is to do this in a ServletContextListener
, but I'd rather not. I want all wiring and setup to stay in one central place without using Listeners.
Is there a way?
The reason for the exception is that the
ServletContext
doesn't exist yet (your server isn't started yet).But there's 2 ways to accomplish this.
Technique 1) Explicit Session Management:
This is probably the more appropriate way to accomplish this for embedded jetty, as you can now control the entire creation / storage / behavior of Sessions.
Technique 2) Use Defaults, Configure HashSessionManager:
For simple web apps this will work just fine.