Search code examples
grailsgrails-2.0grails-controller

Grails - how redirect works?


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.


Solution

  • 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:

    • First public Object redirect(Object instance,Map args) takes map of arguments and is well documented.
    • Second 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 750b360bb242605c1e701a78af9d1bb7e42eeeca

    Implementation of redirect method for latest (2.4.3) release can be found here