[英]Retrieving Grails Domain Validation Messages
I'm pretty new to grails and I'm sure this has been asked multiple times. 我对grails还是很陌生,我敢肯定这已经被问过多次了。 I have an application which I'm developing in grails. 我有一个正在开发的应用程序。 In my service, I make an entry into multiple tables. 在我的服务中,我输入了多个表。 If one of them fails with a mysql unique constraint exception, I get an error as part of domainInstance.errors object. 如果其中之一由于mysql唯一约束异常而失败,我将收到一个错误,这是domainInstance.errors对象的一部分。 How do I parse this to return appropriate error code to my controller. 我该如何解析以将适当的错误代码返回到我的控制器。
Normally in spring, I was generally adding an exception interceptor for controller to take care of this. 通常在春季,我通常会为控制器添加异常拦截器以解决此问题。 Whats the preferred way to do it in grails. 什么是首选的方式来做到这一点。
When a validated domain object has validation errors they are stored under domainObject.errors
, as an implementation of the Spring Errors interface. 当经过验证的域对象具有验证错误时,它们将作为Spring Errors接口的实现存储在domainObject.errors
下。 To render the errors for a field of this object in a GSP, you typically use something like: 要在GSP中呈现此对象字段的错误,通常使用类似以下内容的方法:
<g:hasErrors bean="${book}" field="title">
<div class="errors">
<g:renderErrors bean="${book}" field="title" as="list" />
</div>
</g:hasErrors>
The exact message that is displayed is resolved from the message*.properties
files. 从message*.properties
文件解析了所显示的确切消息。 If you want to get these messages in a controller instead, do this: 如果要在控制器中获取这些消息,请执行以下操作:
class MyController {
MessageSource messageSource
LocaleResolver localeResolver
def myAction(Book book) {
Locale locale = localeResolver.resolveLocale(request)
if (!book.validate()) {
List allErrorMessages = book.errors.allErrors.collect {
messageSource.getMessage(it, locale)
}
// print all error messages
println allErrorMessages
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.