Session management in Dropwizard 0.8.x

2019-07-05 05:27发布

Can someone give me insight of how do I implement session management in Dropwizard 0.8.x or above. I was using Dropwizard 0.7.0 till now and working perfectly in it. But I really confused by change docs provided when I migrated to 0.8.x.

In Dropwizard 0.7.0 (which I was using previously) it was done like the following

/*MainApplication.class session handler */
environment.jersey().register(HttpSessionProvider.class);
environment.servlets().setSessionHandler(new SessionHandler());


/*Resource.class session check*/
HttpSession session = httpServletRequest.getSession(true);

But it does not seems working anymore, precisely saying HttpSessionProvider.class is not there and replaced by some other implementations.

It would be really helpful someone show to what this is changed to. Thanks.

2条回答
相关推荐>>
2楼-- · 2019-07-05 05:59

The reason this isn't working for you is because you need to set the cookie in the response. I noticed this while looking into enabling session state for a dropwizard application where the underlying cookie gets created on the Jetty Response object but it never makes it's way onto the Jersey Response object and therefor gets dropped.

What I've done to work around this issue is to implement a Filter that extracts the "Set-Cookie" information from Jetty and puts it onto the outbound response object.

                String cookie = HttpConnection.
                    getCurrentConnection()
                    .getHttpChannel()
                    .getResponse()
                    .getHttpFields().get(HttpHeader.SET_COOKIE.asString());

            if (LOG.isDebugEnabled()) {
                LOG.debug("Adding session cookie to response for subsequent requests {}", cookie);
            }

            httpServletResponse.addHeader(HttpHeader.SET_COOKIE.asString(), cookie);
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-07-05 06:04

@Yashwanth Krishnan

I know this is old but I noticed that the session was not maintained from one URL to another, simply add this code when you init the application, session handling is mostly a container thing and not specific to DropWizard.

SessionHandler sessionHandler = new SessionHandler();
sessionHandler.getSessionManager().setMaxInactiveInterval(SOME_NUMBER);

    /**
     * By default the session manager tracks sessions by URL and Cookies, we 
     * want to track by cookies only since
     * we are doing a validation on all the app not URL by URL.
     */
    sessionHandler.getSessionManager().setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE));

    environment.servlets().setSessionHandler(sessionHandler);
查看更多
登录 后发表回答