How to use path variables in grails controller?

I am trying to use the path variable in the grails controller, but I cannot reach it. The idea is to check the parameter provided on the URL, which I need to make mandatory. I could not achieve this through RequestParam, so I switched to PathVariable so that the URL presented without the required parameter was filtered by the grails controller itself, instead of adding if / else checks for validity.

So, I can illustrate as below: My url is as follows: -

'<appcontext>/<controller>/<action>?<paramName>=<something>'

Now, to make make "paramName" mandatory, I find no way in Grails (Spring MVC provides @RequestParam annotation, which can let me for "required" as true).

Another alternative, I thought, was to use path variables so that "paramName" could be included in the URL itself. So I tried the following:

'<appcontext>/<controller>/<action>/$paramName'

To check the above URL, I wrote a specific mapping, but some of them do not work.

The following is the specific mapping I wrote: -

"/<controllerName>/<action>/$paramName" {
            controller:<controller to take request>
            action:<action to do task>
            constraints {
                paramName(nullable: false,empty:false, blank: false)
            }
        }

I tried using spring annotation as @PathVariable and @RequestParam in the controller as below: -

 def action(@PathVariable("paramName") String param){
        //code goes here
    }
+4
source share
1 answer

, , Grails ...

// In UrlMappings.groovy
"/foo/$someVariable/$someOtherVariable" {
    controller = 'demo'
    action = 'magic'
}

:

// grails-app/controllers/com/demo/DemoController.groovy
class DemoController {
    def magic(String someOtherVariable, String someVariable) {
        // a request to /foo/jeff/brown will result in
        // this action being invoked, someOtherVariable will be
        // "brown" and someVariable will be "jeff"
    }
}

, .

EDIT:

...

- , , ...

import grails.web.RequestParameter
class DemoController {
    def magic(@RequestParameter('someVariable') String s1, 
              @RequestParameter('someOtherVariable') String s2) {
        // a request to /foo/jeff/brown will result in
        // this action being invoked, s2 will be
        // "brown" and s1 will be "jeff"
    }
}
+12

Source: https://habr.com/ru/post/1546847/


All Articles