grails:url_mappings

URL Mappings

Here will will talk about how to map an URL to our method in our controller with parameter.

We add /myController/myMethod/$var1?/$var2?/$var3? in our mapping. This tell Grails when that when the input URL match to this pattern, we should go to myController, and call myMethod. Notice that we have $var1, $var2, and $var3 in the URL, those are the parameter in URL that we pass to the method. The ? after each variable means those parameter are option.

   static mappings = {
        "/myController/myMethod/$var1?/$var2?/$var3?"{
            controller = "myController"
            action = "myMethod"
        }
        "/$controller/$action?/$id?(.$format)?"{
            constraints {
                // apply constraints here
            }
        }

        "/"(view:"/index")
        "500"(view:'/error')
        "404"(view:'/notFound')
    }

Here we use @RequestParameter('var1') String v1 and so on in the method parameter to obtain the value pass from the URL. Note that var1, var2, and var3 must be the same as what we setup in the UrlMappings.groovy.

package hello

import grails.web.RequestParameter

class MyControllerController {

    def myMethod(@RequestParameter('var1') String v1,
              @RequestParameter('var2') String v2,
              @RequestParameter('var3') String v3) {
        String s = request.getRequestURI()
        render(s + "<br>" + v1 + "<br>" + v2 + "<br>" + v3)
    }
}

The result for URL http://127.0.0.1:8080/myController/myMethod/1a/2b/3c would look like:

/myController/myMethod/1a/2b/3c
1a
2b
3c
  • grails/url_mappings.txt
  • Last modified: 2019/11/22 09:43
  • by chongtin