Reputation: 103
I would like to store a List to a session so I can access it and add/remove/delete objects in a separate controller upon request. I currently have a Controller that is creating a List and outputting it to a JSON, which I am then accessing from a jsp page using AngularJS.
I have tried using @SessionAttributes
by adding the List to a Model, but the List is not stored correctly. I am fairly new to SpringMVC so any suggestions/advice on where to look would be appreciated.
My Controller creating my List:
@RestController
@SessionAttributes({"URLparam", "usersList"})
public class ReportController {
@RequestMapping(value="/events")
public List<Appliance> getEvents(@ModelAttribute("URLparam")String userInput, ModelMap model){
List<Appliance> events = new ArrayList<>();
events = ProcessChoice.ofList(userInput);
model.addAttribute("usersList", events);
System.out.println(userInput);
return events;
}
}
My Controller that I want to edit the existing list:
@Controller
@SessionAttributes("usersList")
public class EditListController {
@RequestMapping(value="/testing", method=RequestMethod.GET)
public String makeChanges(@RequestAttribute("usersList") List<Appliance> usersList) {
//make changes to list here
for(Appliance p: usersList) {
System.out.println(p.getName());
}
return "testing";
}
}
As it stands the code throws: error 400 - Missing request attribute 'usersList' of type List
I can see there is an option to add a collection<> to the model, but I am not sure how to then store it as it doesn't let me give it a name.
Upvotes: 0
Views: 2264
Reputation: 55
In your ReportController you are storing the list ("events") to the model under the key "usersList". The model acts as data that can be rendered in the view. This way it does not get stored to the Session.
Consider something like: session.setAttribute("usersList", events); in ReportController and the corresponding session.getAttribute("usersList") in the EditListController.
You can also omit the @SessionAttributes-annotation is you do it this way. If you want to use those annotations, get familiar with their scope (where to put them and where to use them) and usage here: http://vmustafayev4en.blogspot.de/2012/10/power-of-springs-modelattribute-and.html and official api doc here: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/SessionAttributes.html and
However storing data in the session might seem a good idea, but is often the reason for high memory footprint of the app if there are many active sessions - just so you know.
Upvotes: 1