我有多个方法的控制器,并使用命令对象来验证参数。但是对于每个方法,我必须调用hasError(),如果它是真正的进程错误(通常意味着重定向到特殊页面)。
class MyController{
def action1(ActionCommandObject cmd){
if(cmd.hasErrors()){
//redirect to special page or throw an Exception
}
// do smth.
render view:'/myview1', model: []
}
def action2(ActionCommandObject cmd){
if(cmd.hasErrors()){
//redirect to special page or throw an Exception
}
// do smth.
render view:'/myview2', model: []
}
// More similar methods
}
是否可以避免每个方法中的进程错误情况?我的意思是如果验证失败然后立即执行一些代码(例如抛出异常或重定向到错误页面)
我试图让命令对象在验证后做一些事情,但我不能因为缺少afterValidate方法(beforeValidate方法存在)
答案 0 :(得分:3)
您可以执行described here:
之类的操作class MyController{
protected Object withCommandChecking( cmd, Closure closure ) {
if(cmd.hasErrors()){
//redirect to special page or throw an Exception
}
return closure.call()
}
def action1(ActionCommandObject cmd){
withCommandChecking( cmd ) {
// do smth.
render view:'/myview1', model: []
}
}
def action2(ActionCommandObject cmd){
withCommandChecking( cmd ) {
// do smth.
render view:'/myview2', model: []
}
}
}