Possible Duplicate:
Dependency injection in FacesValidator (JSF Validation)
Maybe, I'm missing something basic - but can't I use injection in a custom validator class in order to use the message resources? The following code gives me a null on msg
, so injection obviously does not work, but why? And if it's not possible, how can I access the message resources? All examples I found so far, use hard coded text in validator messages which is not very useful for localization.
public class BirthdateValidator implements Validator {
@Inject
private transient ResourceBundle msg;
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if ( [some validation fails] ) {
FacesMessage message = new FacesMessage(msg.getString("validator.birthday"));
message.setSeverity(FacesMessage.SEVERITY_ERROR);
}
}
}
As to why it doesn't work that way, see this answer: How to inject in @FacesValidator with @EJB, @PersistenceContext, @Inject, @Autowired. In a nutshell, annotate it @Named
instead of @FacesValidator
and reference it in <h:inputXxx validator>
or <f:validator binding>
as #{birthdateValidator}
instead. The problem is caused by an oversight by JSF/CDI guys. This is fixed in upcoming JSF 2.2.
Ok since I only need to access the message bundle, how would I access it without injection?
Evaluate it programmatically using Application#evaluateExpressionGet()
:
ResourceBundle msg = context.getApplication().evaluateExpressionGet(context, "#{msg}", ResourceBundle.class);
// ...
You can even pick a specific key:
String msg = context.getApplication().evaluateExpressionGet(context, "#{msg.key}", String.class);
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With