2013-08-03 36 views
1

我希望把由Bean驗證(JSR 303)用於驗證消息例:將驗證消息到數據庫

javax.validation.constraints.AssertFalse.message=must be false 
javax.validation.constraints.AssertTrue.message=must be true ... 

到數據庫中,這樣,當管理員添加一個新的語言,他可以增加對翻譯那種語言。

我知道如何訪問從數據庫映射的資源包,但我無法弄清楚如何擴展/定製Bean驗證類,使他們能夠訪問數據庫中的驗證消息...

是有可能獲得我想要的?

非常感謝提前把我推向正確的方向。

這裏的解決方案(我不知道這是最好的解決方案,但它的工作原理...):

至於建議由@gastaldi我創建MessageInterpolator接口的實現:

package giates.validation; 

import com.infomaxgroup.adaecommerce.bundles.DatabaseResourceBundle; 
import java.util.Locale; 
import java.util.Map; 
import javax.validation.MessageInterpolator; 

public class LocaleMessageInterpolator implements MessageInterpolator { 
    protected final String BRACE_OPEN = "\\{"; 
    protected final String BRACE_CLOSE = "\\}"; 

    @Override 
    public String interpolate(String message, Context context) { 
    return interpolate(message, context, Locale.ITALIAN); 
    } 

    @Override 
    public String interpolate(String message, Context context, Locale locale) { 
    DatabaseResourceBundle bundle = new DatabaseResourceBundle(locale); 
    String messageKey = context.getConstraintDescriptor().getAttributes().get("message").toString(); 
    message = bundle.getString(messageKey.replaceAll(BRACE_OPEN, "").replaceAll(BRACE_CLOSE, "")); 
    Map<String, Object> attributes = context.getConstraintDescriptor().getAttributes(); 
    for (String key : attributes.keySet()) { 
     String value = attributes.get(key).toString(); 
     key = BRACE_OPEN + key + BRACE_CLOSE; 
     message = message.replaceAll(key, value); 
    } 
    return message; 
    } 
} 

然後我創建META-INF/validation.xml中,並加入定製的messageinterpolator:只要我發佈一個模型校驗失敗,插值呼叫

<?xml version="1.0" encoding="UTF-8"?> 
<validation-config 
    xmlns="http://jboss.org/xml/ns/javax/validation/configuration" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration"> 
    <message-interpolator>giates.validation.LocaleMessageInterpolator</message-interpolator> 
</validation-config> 

s DatabaseResourceBundle並創建結果消息...

所有的作品都很棒!

回答

1

您需要創建一個定製的MessageInterpolator爲和你validator.xml配置

+0

而且可能是一個資源包專業化以及 – gastaldi

+0

檢查了這一點:https://forum.hibernate.org/viewtopic.php?p = 2442703 – gastaldi

+0

而這個:http://musingsofaprogrammingaddict.blogspot.com.br/2010_06_01_archive.html – gastaldi