Search code examples
grailsgrails-controllergrails-3.0

Grails Controller Mapping, Complete misunderstanding


Okay, I'm trying to learn grails and I don't get how does UrlMappings work.

This is my code:

package naturalselector

class UrlMappings {

static mappings = {
    "/pleasemapit"(view: '/index')
    "/creatures/" {
      controller = 'NaturalSelectionController'
      action = 'viewCreatures'
    }
    "500"(view:'/error')
    "404"(view:'/notFound')
}
}

Controller class:

package naturalselector

class NaturalSelectionController {

def viewCreatures() {
  println("HIT viewCreatures")
  List creatures
  6.times { idx ->
    creatures.add(new RandomCreature())
    println creatures.get(idx)
  }
  redirect (view: "/index")
}
}

controller is in grails-app\controllers\naturalselector\ UrlMappings are in the same dir.

In all examples controller has a lower case value. I don't understand. Is it a package? Why would you specify controller as a package? I just want to execute method in controller, I don't want to render any page yet, just redirect back to index. Thank you.


Solution

  • Is it a package?

    No.

    Why would you specify controller as a package?

    You wouldn't.

    Instead of this...

    static mappings = {
        "/pleasemapit"(view: '/index')
        "/creatures/" {
            controller = 'NaturalSelectionController'
            action = 'viewCreatures'
        }
        "500"(view:'/error')
        "404"(view:'/notFound')
    }
    

    Use this...

    static mappings = {
        "/pleasemapit"(view: '/index')
        "/creatures" {
            controller = 'naturalSelection'
            action = 'viewCreatures'
        }
        "500"(view:'/error')
        "404"(view:'/notFound')
    }
    

    Or this...

    static mappings = {
        "/pleasemapit"(view: '/index')
        "/creatures"(controller: 'naturalSelection', action: 'viewCreatures')
        "500"(view:'/error')
        "404"(view:'/notFound')
    }