Embedded Jetty: How do I call setSessionTrackingModes without a ServletContextListener

1.5k views Asked by At

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?

1

There are 1 answers

1
Joakim Erdfelt On BEST ANSWER

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:

    Server server = new Server(8080);

    // Specify the Session ID Manager
    HashSessionIdManager idmanager = new HashSessionIdManager();
    server.setSessionIdManager(idmanager);

    // Create the SessionHandler to handle the sessions
    HashSessionManager manager = new HashSessionManager();
    manager.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE)); // <-- here
    SessionHandler sessions = new SessionHandler(manager);

    // Create ServletContext
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setSessionHandler(sessions); // <-- set session handling
    server.setHandler(context);

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:

    Server server = new Server(8080);

    // Create ServletContext
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.getSessionHandler()
           .getSessionManager()
           .setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE));
    server.setHandler(context);

For simple web apps this will work just fine.