Reputation: 599
In grails documentation in paragraph Implementing the 'save' action there is following snippet of code:
book.save flush:true
withFormat {
html {
flash.message = message(code: 'default.created.message', args: [message(code: 'book.label', default: 'Book'), book.id])
redirect book
}
'*' { render status: CREATED }
}
There is also note that:
In the case of HTML a redirect is issued to the originating resource and for other formats a status code of 201 (CREATED) is returned.
I am curious about redirect part and HTML. In code there is domain object (book) passed as argument to redirect method. When executed we are redirected to details of saved book.
I suppose that above redirect code it equivalent to:
redirect(action: "show", id: book.id)
So how Grails knows what is "originating resource"? Is there a simmilar behavior as for respond method and Content Negotiation?
Unfortunately I can't find answer at redirect method documentation.
Upvotes: 2
Views: 1169
Reputation: 599
After some time of debbuging and grepping Grails code I have found answer. I have also found this post: http://www.bl-nk.net/2014/04/explicit-redirect-grails/ which is helpful.
Redirect method is overloaded and has two forms:
public Object redirect(Object instance,Map args)
takes map of arguments and is well documented.public Object redirect(Object instance,Object object)
takes an object and if it is a domain class then grails redirects to show view for corresponding controller. And it is method that I was looking for. It was introduced in commit 750b360bb242605c1e701a78af9d1bb7e42eeecaImplementation of redirect method for latest (2.4.3) release can be found here
Upvotes: 3
Reputation: 75671
That information is available in the org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest
which is created for each request, partially by Grails and partially by Spring (the Grails class extends Spring's org.springframework.web.servlet.handler.DispatcherServletWebRequest
) and the instance is made available in a ThreadLocal
. So since each request is on its own thread, they're all isolated from each other, and it's convenient to access the data if you know where the thread-locals are. Spring Security's SecurityContext
, Hibernate's Session, any current running transaction, and the active JDBC connection if one was borrowed are other examples of data stored under well-known thread-local keys for convenient access.
The GrailsWebRequest
has a GrailsParameterMap
instance - that's the params
map you see in controllers, and if you run println params
from a controller action you'll see that in addition to your paramter values, the controller and action name are there too. It also has references to the request, response, session, etc. So it's pretty easy to know the current state from that.
Upvotes: 1