如何在约束自定义验证中访问URL映射参数?

时间:2018-10-07 15:01:59

标签: grails

在grails 2.2.3应用程序中,我具有以下网址映射

$locations = DB::table('locations_categories as lc')
    ->join('locations', 'locations.id', '=', 'lc.location_id')
    ->whereIn('lc.category_id', $request->categories)
    ->selectRaw('locations.name, locations.id, locations.lon, locations.lat,'
        . 'lc.category_id as catId,'
        . 'lc.location_id as locId,'
        . 'haversine(?, ?, locations.lon,locations.lat) as distance',
    [$request->lon, $request->lat])
->get();

我需要在学校参数中实现自定义验证。为此,我需要调用userService.getUserSchools(id)方法。

当前尝试给import app.UserService class UrlMappings { UserService userService static mappings = { ctx -> "/users/$id/records/$school/detail" { controller = 'user' action = 'recordsDetail' constraints { id matches: /\d+/ school validator: { school, obj -> school in ctx.userService.getUserSchools(id) } } } } } 加上消息java.lang.NullPointerException,我需要在学校自定义验证器中访问Cannot get property 'id' on null object参数。我尝试了idid,但没有成功。

谢谢您的建议

1 个答案:

答案 0 :(得分:0)

obj在这种情况下是RegexUrlMapping,它不允许访问id参数,但是您可以使用org.springframework.web.context.request.RequestContextHolder来访问验证程序闭包内的任何请求参数,如下所示:

RequestContextHolder.requestAttributes.params.id

或者只是:

RequestContextHolder.requestAttributes.id