gpt4 book ai didi

validation - 以DRY方式为每个请求验证RESTful URL

转载 作者:行者123 更新时间:2023-12-02 14:42:12 25 4
gpt4 key购买 nike

我们的Grails 2.4.4应用程序始终使用RESTful URL。给定以下URL:

/ stores / 123 / products / 456

我想验证是否有一个ID为123的商店,如果没有,请在对Product Controller 的每次请求中重定向到404。我既不必将存储查找代码放在每个操作方法中,也不想创建 Controller 基类,因为那样我就必须在每个操作方法中放置一个方法调用。

可以通过拦截器完成吗?

最佳答案

拦截器是在Grails 3.0中引入的。您将在Grails 2.4.4中需要filters
before = { }是这里需要的。

还请查看文档,默认情况下哪些变量可用于过滤器(例如:params,request,response等)。如果仍然不清楚,我可以添加一个答案作为示例。但我希望文档能自我解释。作为一个例子,我会这样做

class EntityCheckFilters {
def filters = {
storeExistCheck( controller:'product' ) {
before = {
if ( !params.storeId || !Store.exists( params.sotreId as Long ) ) {
response.sendError(404)
// or for example if you have a separate action to handle 404
// redirect(action: 'handle404')

// this is important,
// because we do not want to pass through with the original call
return false
}
}
}
}
}

关于validation - 以DRY方式为每个请求验证RESTful URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29131676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com