Grails: the best approach for storing data for a user session

Which of the following methods is considered the recommended way to store data in grails during a user session?

  • Store a bunch of separate variables in the current session.
  • Save the domain model class object in the session.
  • Use a controller with scope and save the variables as fields or properties of the controller.
  • Use a controller with scope and save the data as an object of the domain model class stored in the controller.
  • Some other ways that I have not thought about.
+7
session grails controller domain-model
source share
2 answers

I like to use session services for this kind of thing. With this approach, you enter a proxy server for your service with session coverage in the global coverage area (or controller), which means you don’t have to worry about tracking the material you entered into the session.

Here is a good tutorial here that shows how to mix services with different levels of coverage. And it looks like the author of this tutorial also wrote a plugin to make the process easier (I haven't tried the plugin at all).

EDIT:

Here is an example showing how you configured it and actually use the service proxy to convey material to your view:

Create a service that will store your materials related to the session, for example, in the users basket or whatever. This is just a regular service (which refers to other services, etc.), but you can store the session related data as member variables -

class MySessionScopedService { def currentUser def shoppingCart ... } 

In resources.groovy configure a proxy server for your service. Instead of directly entering MySessionScopedService into other services, you will be introducing a proxy server for it.

 beans = { mySessionScopedServiceProxy(org.springframework.aop.scope.ScopedProxyFactoryBean) { targetBeanName = 'mySessionScopedService' proxyTargetClass = true } } 

Finally, when you want to reference your service, you refer to the proxy (note that I refer to mySessionScopedServiceProxy , not MySessionScopedService ). You can reference the proxy server in any component with global reach and at run time, Spring will enter the correct one for the current session.

 class MyController { def mySessionScopedServiceProxy def someOtherService def index() { [shoppingCart: mySessionScopedServiceProxy.shoppingCart, currentUser: mySessionScopedServiceProxy.currentUser] } } 
+3
source share

As Sudir has already pointed out, a card stored directly in a session is for me the easiest and most anticipated way.

0
source share

All Articles