如何在grails控制器中使用路径变量?

Vis*_*hal 4 parameters grails grails-controller

我一直在尝试在grails控制器中使用路径变量,但我无法实现它.背后的意图是验证提交给我需要强制的URL的参数.我无法通过RequestParam实现它,所以我切换到PathVariable,以便提交没有所需param的url应该由grails控制器本身过滤掉,而不是我添加if/else检查有效性.

所以,我可以说明如下:我的网址如下: -

'<appcontext>/<controller>/<action>?<paramName>=<something>'
Run Code Online (Sandbox Code Playgroud)

现在,为了使'paramName'成为强制性的,我没有在Grails中找到任何方法(Spring MVC提供了@RequestParam注释,它可以使我''required'为真).

我认为另一种选择是使用路径变量,以便'paramName'可以包含在URL本身中.所以我试着跟随:

'<appcontext>/<controller>/<action>/$paramName'
Run Code Online (Sandbox Code Playgroud)

为了验证上面的URL,我编写了特定的映射,但有些映射不起作用..

以下是我写的具体映射: -

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

我尝试在控制器中使用类似@PathVariable和@RequestParam的弹簧注释,如下所示: -

 def action(@PathVariable("paramName") String param){
        //code goes here
    }
Run Code Online (Sandbox Code Playgroud)

Jef*_*own 13

如果您将方法参数命名为与请求参数重命名相同,Grails将为您处理它...

// In UrlMappings.groovy
"/foo/$someVariable/$someOtherVariable" {
    controller = 'demo'
    action = 'magic'
}
Run Code Online (Sandbox Code Playgroud)

然后在你的控制器中:

// 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"
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望有所帮助.

编辑:

另外一个选项...

如果由于某种原因你想要方法参数的不同名称,你可以显式地将方法参数映射到这样的请求参数...

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"
    }
}
Run Code Online (Sandbox Code Playgroud)