This is a note to remind me the right way to understand the right way of using @sessionattribute.

SessionAttribte is not designed to deal with session

I found some articles online but some are so clear, I keep some note here to avoid misleading again. The design of session attibute is not to help client to store form base information rather than deal with session itself.

Spring want to keep its technical independence. it introduced handlers to deal with the model objects. So it could use another technique rather than session or request model by injecting another handler, that is a good feature.

However, it also introduced some wired way to synchronize the model data with backend real way of store data. It have to copy bewteen handler and real data. Just like below code from spring mvc, it introduced mvcContainer to synchronize data.

public void updateModel(NativeWebRequest request, ModelAndViewContainer mavContainer) throws Exception {

    if (mavContainer.getSessionStatus().isComplete()){
        this.sessionAttributesHandler.cleanupAttributes(request);
    }
    else {
        this.sessionAttributesHandler.storeAttributes(request, mavContainer.getModel());
    }

    if (!mavContainer.isRequestHandled()) {
        updateBindingResult(request, mavContainer.getModel());
    }
}

Session attibute is designed to solve the problem of multiple page form filling.

it is suggested to use session attribute to just handle form information, becasue it is clear to use this annotation in one controller but not so clear crossing the controller.

There is a potential problem of using session attribute to deal with common session. If we inject the session in the controller use @sessionattribute and @httpsession at the sametime, values managed by both @sessionattribute and @httpsession the change will finnally be restored by spring mvc if we forget set the status complete.

Right way to dealwith Session

Inject HttpSession in parameter, and deal with that directly. Don’t use @SessionAttribute to deal with common session.

Leave me a message

comments powered by Disqus

Published

Category

Programming

Tags