问题
I'm creating a JSF 2-application and I'm trying to use form validation in the bean instead of the faces-page. I'd also like to use a .properties file to store the messages.
I looked at this question but I don't think I have the properties-file set up correctly.
Let's say I have a bean called User in a package called 'dev':
@ManagedBean
@SessionScoped
public class User implements Serializable {
@Pattern(pattern=".+@.+\\.[a-z]+", message="{dev.User.emailAddress}")
private String emailAddress;
// getter/setter
}
I've also created a file 'ValidationMessages.properties' in WEB-INF/classes (I'm using Netbeans 7.0.1)
In the ValidationMessages.properties file I've got this key/value-line:
dev.User.emailAddress=Custom invalid email message
And my view (user.xhtml) looks like this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>User registration</title>
</h:head>
<h:body>
<h:form>
<h:inputText id="emailAddress" value="#{user.emailAddress}" required="true" />
<h:message for="emailAddress" />
<h:commandButton value="Ok" action="null" />
</h:form>
</h:body>
When I enter an invalid email and press the button, the validation message in the web page reads:
{dev.User.emailAddress}
instead of
Custom invalid email message
Could the problem be that I haven't registered my properties file in web.xml?
I should switch required="true" to @NotNull in the bean too. Is there anything more I need to do than insert this:
<context-param>
<param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
<param-value>true</param-value>
</context-param>
as explained in BalusC's blog?
Thanks in advance!
/ Dennis
回答1:
I've also created a file 'ValidationMessages.properties' in WEB-INF/classes (I'm using Netbeans 7.0.1)
I understand that you've put it straight in the project's /WEB-INF/classes
folder yourself? This will likely be ignored/overridden if you let your IDE build/deploy the WAR (at least, this is true for Eclipse). You should rather put that file straight in the root of the Java source folder of the project. You can verify yourself if it really ended up in /WEB-INF/classes
, after you export the project to a WAR file and then extract it using some ZIP tool.
回答2:
I placed the .properties file in the resources folder and it worked, there was no need to register the file anywhere. For the record: I'm using Netbeans 7.0.1 and Maven.
Thanks for the help, BalusC!
来源:https://stackoverflow.com/questions/8048710/custom-validation-message-for-bean-validation