私のアプリケーションでは、多くのクラスに共通のフィールド「company」があります。アプリケーションがそのオブジェクトを保存するとき、それらは会社で満たされなければなりません(そのための検証があります)。会社もセッションに参加しています。ここで、ドメインクラスをコマンドオブジェクトとして使用する場合、会社はすでに入力されている必要があります。そうしないと、検証エラーが発生します。検証が行われる前に常に会社のフィールドに入力する方法はありますか?そのため、毎回手動で入力する必要はありませんでした。(カスタムデータバインダーを試しましたが、リクエストにパラメーターがない場合は機能しません)
2 に答える
1
オブジェクトが保存、更新、またはGORMイベント を使用して検証される直前に、プロパティを設定できます。beforeInsert
beforeUpdate
beforeValidate
あなたのドメインでは、次のようなものが必要です。
import org.springframework.web.context.request.RequestContextHolder
class Foo {
String company
...
def beforeInsert = {
try {
// add some more error checking (i.e. if there is is no request)
def session = RequestContextHolder.currentRequestAttributes().getSession()
if(session) {
this.company = session.company
}
} catch(Exception e) {
log.error e
}
}
}
于 2012-05-31T09:41:03.933 に答える
1
バインドプロセスの前にプロパティをバインドする場合は、カスタムBindEventListenerを作成して、 grails-app / conf / spring/resources.groovyに登録できます。
まず、カスタムBindEventListenerを作成します
/src/groovy/SessionBinderEventListener.groovy
import org.springframework.beans.MutablePropertyValues
import org.springframework.beans.TypeConverter
class SessionBinderEventListener implements BindEVentListener {
void doBind(Object wrapper, MutablePropertyValues mpv, TypeConverter converter) {
def session = RequestContextHolder.currentRequestAttributes().getSession()
mpv.addPropertyValue("company", session.company)
}
}
次に、BindEventListenerを登録します
grails-app / conf / spring / resources.groovy
beans = {
sessionBinderEventListener(SessionBinderEventListener)
}
ただし、ドメインクラスがcompanyというプロパティを保持していない場合は、InvalidPropertyExceptionが発生します。この問題を解決するには、companyというプロパティを含むクラスのリストを作成します-以下の詳細を参照してください
/src/groovy/SessionBinderEventListener.groovy
import org.springframework.beans.MutablePropertyValues
import org.springframework.beans.TypeConverter
class SessionBinderEventListener implements BindEVentListener {
private List<Class> allowedClasses = [Foo]
void doBind(Object wrapper, MutablePropertyValues mpv, TypeConverter converter) {
if(!(allowedClasses.contains(wrapper.class))) {
return
}
def session = RequestContextHolder.currentRequestAttributes().getSession()
mpv.addPropertyValue("company", session.company)
}
}
于 2012-11-24T04:19:34.943 に答える