Skip to content
Advertisement

Store and retrieve an object in session through @Scope(“session”)

I am having a Spring shopping project and I am working on a cart with I can add new product to it and store it in the session. I create a Cart class to store it in the session

JavaScript

I create a Controller class to get the cart from session and add product to it

JavaScript

But when I call this controller it send back an error

JavaScript

Advertisement

Answer

I think the NullPointerException is caused by you didn’t initialize the “productlist”. You can try something like this: “private HashMap<Integer,Product> productlist = new HashMap<>();“.

It’s ok to use the “session scope” on the cart without specifying the “proxyMode” attribute of the “@Scope” annotation, if the “request scope” controller is the only bean has an dependency on it.

But usually the Controller should be “singleton” scope, unless you have a good reason for choosing another kind of scope. And if the Controller is “singleton” scope, you should specify the “proxyMode” attribute of the “@Scope” annotation.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement