Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Grails can the flash storage object only be accessed from controllers and views?

Tags:

grails

In Grails the flash storage object is used to hold onto cross request data like messages.

I know that it can be accessed from most Views and Controllers, but I'm not sure if it's available universally across Grails, or if it can only be accessed from certain conventional objects.

Can the flash object be accessed from Services, for instance?

Or even anywhere during a live web request?

What are it's precise limitations in terms of access?

like image 499
Mark Rogers Avatar asked Jun 17 '11 22:06

Mark Rogers


2 Answers

You can gain access to the flash wherever, and more importantly, whenever you have access to a web request. In general, you can get the flash from the GrailsWebRequest object.

import org.codehaus.groovy.grails.web.util.WebUtils

def grailsWebRequest = WebUtils.retrieveGrailsWebRequest()
// request is the HttpServletRequest
def flash = grailsWebRequest.attributes.getFlashScope(request)

If you invoke retrieveGrailsWebRequest() outside the context of a web request, you'll get an IllegalStateException. The GrailsWebRequest is bound to the current thread by a filter, GrailsWebRequestFilter, which is executed early in the service request. So basically, as long as you're in the context of a request and "inside" this filter execution, you should be able to access the flash.

Beyond that, take a look at the source for org.codehaus.groovy.grails.web.servlet.DefaultGrailsApplicationAttributes. The flash storage is saved in the session, so theoretically you should be able to use it once you gain access to the session. Be careful though, since it's shared among the different request for the session. The mentioned filter is responsible for advancing the state of the flash throughout requests, essentially popping a ConcurrentHashMap from a 2-element queue.

like image 122
Gustavo Giráldez Avatar answered Oct 21 '22 18:10

Gustavo Giráldez


As long as you're within the context of a request you can access the flash scope with

import org.codehaus.groovy.grails.web.util.WebUtils

def flashScope = WebUtils.retrieveGrailsWebRequest().flashScope

(Grails scripts and Quartz jobs are examples of places in a Grails app that are not within the context of a request)

like image 23
Dónal Avatar answered Oct 21 '22 17:10

Dónal