How to do Versioning Controllers in Grails Example

Points To Remember


  • Versioning  of Controllers can be done in grails with the help of UrlMappings and Namespaces.
  • We can have two or more controllers with the same name as long as they are in different packages and different namespaces.
  • You can map these controllers in UrlMappings like /$namespace/$controller/$action

Versioning of Grails Controllers 

The easiest way of versioning the grails controllers is to do it with the help of namespaces. So in this example we will try to do versioning of the controllers on the basis of namespaces.
Test.groovy
package com.ekiras.versioning.v1

class TestController {

    static namespace = "v1"

    def index() {
        render "Hi, This is version 1"
    }
}

Test.groovy
package com.ekiras.versioning.v2

class TestController {

    static namespace = "v2"

    def index() {
        render "Hi, This is version 2"
    }
}

UrlMappings
class UrlMappings {

 static mappings = {

        "/$namespace/$controller/$action?/$id?(.$format)?"{
            constraints {
                // apply constraints here
            }
        }


        "/$controller/$action?/$id?(.$format)?"{
            constraints {
                // apply constraints here
            }
        }

        "/"(view:"/index")
        "500"(view:'/error')
//        Other Mappings
 }
}

So now we can call the two different controllers with the same name but different namespaces.
For example, if we run our app at root context at port 8080, then we can access these like following

http://localhost:8080/v1/test
http://localhost:8080/v2/test

No comments :

Post a Comment