我正在创建一个 JSF 2 应用程序,并且尝试在 bean 中而不是 faces-page 中使用表单验证。我还想使用 .properties 文件来存储消息。
我在看这个问题 https://stackoverflow.com/questions/2235544/bean-validation-and-error-messages-at-properties-file但我认为我没有正确设置属性文件。
假设我有一个名为 User 的 bean,位于名为“dev”的包中:
@ManagedBean
@SessionScoped
public class User implements Serializable {
@Pattern(pattern=".+@.+\\.[a-z]+", message="{dev.User.emailAddress}")
private String emailAddress;
// getter/setter
}
我还在 WEB-INF/classes 中创建了一个文件“ValidationMessages.properties”(我使用的是 Netbeans 7.0.1)
在 ValidationMessages.properties 文件中,我有这个键/值行:
dev.User.emailAddress=Custom invalid email message
我的视图(user.xhtml)如下所示:
<!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>
当我输入无效电子邮件并按下按钮时,网页中的验证消息显示:
{dev.User.emailAddress}
代替
Custom invalid email message
问题可能是我没有在 web.xml 中注册我的属性文件吗?
我也应该在 bean 中将 required="true" 切换为 @NotNull 。除了插入以下内容之外,我还需要做些什么吗?
<context-param>
<param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
<param-value>true</param-value>
</context-param>
如中所解释的BalusC 的博客 http://balusc.blogspot.com/2011/09/communication-in-jsf-20.html?
提前致谢!
/ Dennis