Spring MVC - difference between HttpSession.setAttribute and model.addObject

☆樱花仙子☆ 提交于 2019-12-03 07:33:56

First of all, @SessionAttribute does not have to use the http session. It uses a SessionAttributeStore which can have anything as its backing storage. Only the default implementation uses the http session.

The reason why your code does not work as expected lies in how @SessionAttribute works.

Before a controller method is invoked, everything listed in @SessionAttributes, in your case {"warenkorb", "count"}, is read from the session and added to the model.

After the method has returned the session is updated with everything that has been added to the model within the method.

.addObject("count", count)

-> count is added to the model and afterwards to the session.

session.setAttribute("count", count)

-> count is added to the session but not to the model. It will be added to the model before the next invocation of any controller method. But as for now the model still has the old count. And the model is what gets added to the request. And if an attribute can be found in the request scope then the jsp does not care about what's in the session.

When you use @SessionAttributesand @ModelAttribute (or Spring MVC in general) then avoid using HttpSession or HttpRequest. Even HttpResponseis of limited use. Embrace the beauty of Spring MVC instead :)

model.addObject puts object to the request scope while HTTPsession.setAttribute puts it to the session scope. And since variables on jsp are resolved on the next order: page scope -> request scope -> session scope -> application scope, you get what you get.

Java method params are passed by values. You can assign to this paramateter anything yoou want inside the method, but it won't have ny effect outside of it . Insisde of the method you're dealing with the copy of the param

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!