Reputation:
I have a web application and front-end makes ajax request to server in order to get data. In controller I have following logic:
def data = []
def method() {
def objects = []
...
from params determine if it is a first request
...
if (firstRequest) {
objects = someService.getObjectFromDB()
data = objects
} else {
actions with data object
}
But the problem is that for the 2+ requests data
is an empty list despite the fact that during the first request I populate it with needed information. How can I use data
object is 2+ requests?
Upvotes: 1
Views: 3001
Reputation: 50245
I would suggest to move the above logic from the controller to the service class. Benefits of doing this:-
1.Service is by default singleton. You can set the scope to request
as a result of which you would get an handle to the global data per request.
2.Session will not be overloaded with data.
3.Best part:- You can pass in params
&/| request
(defaults of a Controller) to service layer in method calls.
Upvotes: 1
Reputation: 15909
Store the data object in the user sessions like:
session.data = objects
And when you enter the method check of the data is already there..
if (!session?.data) {
// first request
objects = someService.getObjectFromDB()
session.data = objects
} else {
// retrieve data from session
def oldData = session.data
// do something
}
This is probably not the best solution because you will store a lot of information in the session so try to restrict that to a minimal.
Upvotes: 3