<< Hosting/Deploying Ruby On Rails apps on Windows | Home | Displayport port >>

Grails 1.1.1 URL mapping and reverse mapping example

As there's not many examples of Grails 1.1.1 URL Mappings and examples of using them from within GSP files I thought I'd share this one with everyone.

When reading up on URL mappings I found a few inconsistencies between the books I was reading, the examples that are out there and the documentation and the fact there's two ways to specify a controller for a given mapping.

This example uses a closure to specify the controller as a property.

class UrlMappings {
    static mappings = {
        "/trip/$tripId/coordinate/$action" {
            controller = 'coordinate'
        }
    }
}

This next example uses a list to specify the controller as a parameter.

class UrlMappings {
    static mappings = {
        "/trip/$tripId/coordinate/$action" (
            controller: 'coordinate'
        )
    }
}

Both examples are equivalent and in the "Definite Guide to Grails 2nd Edition" the author says it's personal preference which one you use.  I personally prefer the former, and in a posting to the grails mailing list where this functionality was first announced the former is used.  Here's the link to Graeme Rocher's post: http://www.nabble.com/Reverse-URL-Mapping-td9574124.html

Here's an example of creating link and upload form action urls:

<g:link url="[controller:'coordinate', action:'upload', params: [tripId:trip.id]]" >link text</g:link>
<g:link controller="coordinate" action="upload" params="[tripId:trip.id]">link text</g:link>

<g:uploadForm url="[controller: 'coordinate', action: 'upload', params: [tripId:trip.id]]" >
    <input type="file" name="coordinates" />
    <input type="submit" value="Upload Coordinates" />
</g:uploadForm>

<g:uploadForm controller="coordinate" action="upload" params="[tripId:trip.id]" >
    <input type="file" name="coordinates" />
    <input type="submit" value="Upload Coordinates" />
</g:uploadForm>

All 4 urls that are generated are identical, the url that's generated, given a trip.id of 5 would be:

/your-app/trip/5/coordinate/upload

If this helped you please post a comment, if you have any links to further examples please share them!




Send a TrackBack