Spring-session: Why is the request.commitSession() method called repeatedly?

Created on 6 Sep 2018  路  3Comments  路  Source: spring-projects/spring-session

based on spring-session 2.0.5.RELEASE

There are two code snippets here. eg:

First, for the method of doFilterInternal in SessionRepostoryFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request,
        HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
    request.setAttribute(SESSION_REPOSITORY_ATTR, this.sessionRepository);
    SessionRepositoryRequestWrapper wrappedRequest = new SessionRepositoryRequestWrapper(
            request, response, this.servletContext);
    SessionRepositoryResponseWrapper wrappedResponse = new SessionRepositoryResponseWrapper(
            wrappedRequest, response);
    try {
        filterChain.doFilter(wrappedRequest, wrappedResponse);
    }
    finally {
        wrappedRequest.commitSession();
    }
}

Second, for the method of onResponseCommitted in SessionRepositoryResponseWrapper.java

private final class SessionRepositoryResponseWrapper
        extends OnCommittedResponseWrapper {
    private final SessionRepositoryRequestWrapper request;
    /**
     * Create a new {@link SessionRepositoryResponseWrapper}.
     * @param request the request to be wrapped
     * @param response the response to be wrapped
     */
    SessionRepositoryResponseWrapper(SessionRepositoryRequestWrapper request,
            HttpServletResponse response) {
        super(response);
        if (request == null) {
            throw new IllegalArgumentException("request cannot be null");
        }
        this.request = request;
    }
    @Override
    protected void onResponseCommitted() {
        this.request.commitSession();
    }
}

The request.commitSession() method is called in both places.

why? Is this not a repeated call?

stack-overflow

Most helpful comment

Is this causing you problems? The reason is that we need to ensure that the session is created before the response is committed. If the response is already committed there will be no way to track the session (i.e. a cookie cannot be written to the response to keep track of which session id).

All 3 comments

Is this causing you problems? The reason is that we need to ensure that the session is created before the response is committed. If the response is already committed there will be no way to track the session (i.e. a cookie cannot be written to the response to keep track of which session id).

@rwinch

Thanks, No problem. just me wondering. I understand this logic after reading JavaTM Servlet Specification.

@lixyou On top what @rwinch provided here, you can also find information about this in the _Custom SessionRepository_ section of our reference manual and in this comment.

Was this page helpful?
0 / 5 - 0 ratings