开发者

JSF2: bean validation with custom message bundle

开发者 https://www.devze.com 2023-03-17 20:14 出处:网络
I know the issue is discussed in many posts in the forum, however I\'m still having problems customizing the messages for the bean validation. Maybe some little things missing in configuration or file

I know the issue is discussed in many posts in the forum, however I'm still having problems customizing the messages for the bean validation. Maybe some little things missing in configuration or file location...

When the validation call the messag开发者_C百科e, the web page shows the message ID instead of the message text.

For example I see in the web page {messages.myMessageId}

I have:

src/com/myapp/view/validationvalidation_en.poperties

webuser_name_notnull = Name is required

faces-config.xml

<message-bundle>
        com.myapp.view.validation
</message-bundle>

webuser.java

@NotNull(message = "{webuser_name_notnull}")
private String name;

Many thanks for support!


As per chapter 4.3.1.1 of the JSR303 specification, the custom JSR303 validation messages file needs to have exactly the name ValidationMessages.properties and it needs to be placed in the root of the classpath, in your case thus directly in the src folder.

Please note that Bean Validation is not part of JSF. It's part of Java EE of which JSF is also a part. The JSF <message-bundle> only definies the location of JSF default validation messages (such as the one which you see on required="true"), not the JSR303 Bean Validation messages.


You could use a MessageInterpolator. If you use hibernate try this

public class ResourceBundleMessageInterpolator extends org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator implements
    MessageInterpolator {

  @Override
  public String interpolate(String message, Context context, Locale locale) {
    // evaluate el expression
    if (message != null && message.startsWith("#{")) {
      FacesContext facesContext = FacesContext.getCurrentInstance();
      Application app = facesContext.getApplication();
      ExpressionFactory elFactory = app.getExpressionFactory();
      ELContext elContext = facesContext.getELContext();
      ValueExpression valueExp = elFactory.createValueExpression(elContext, message, Object.class);
      Object value = valueExp.getValue(elContext);
      if (value == null) {
        return null;
      } else {
        return value.toString();
      }
    } else {
      return super.interpolate(message, context, locale);
    }
  }
}

Finally you need META-INF/validation.xml

<?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>package.ResourceBundleMessageInterpolator</message-interpolator>
</validation-config>
0

精彩评论

暂无评论...
验证码 换一张
取 消