本文介绍了bean验证的自定义验证消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个JSF 2应用程序,我正在尝试在bean中使用表单验证而不是faces-page。我还想使用.properties文件来存储消息。

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.

假设我在名为'dev'的软件包中有一个名为User的bean:

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
}

我是还在WEB-INF / classes中创建了一个文件'ValidationMessages.properties'(我正在使用Netbeans 7.0.1)

I've also created a file 'ValidationMessages.properties' in WEB-INF/classes (I'm using Netbeans 7.0.1)

在ValidationMessages.properties文件中我有此键/值行:

In the ValidationMessages.properties file I've got this key/value-line:

dev.User.emailAddress=Custom invalid email message

我的观点(user.xhtml)如下所示:

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}

而不是

Custom invalid email message

问题可能是我没有在web.xml中注册我的属性文件?

Could the problem be that I haven't registered my properties file in web.xml?

我也应该在bean中将required =true切换为@NotNull。还有什么比插入这个更多我需要做的事情:

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>

,如?

提前致谢!

/ Dennis

推荐答案

我将.properties文件放入资源文件夹,它工作,没有必要在任何地方注册文件。记录:我使用的是Netbeans 7.0.1和Maven。

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.

感谢您的帮助,BalusC!

Thanks for the help, BalusC!

这篇关于bean验证的自定义验证消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 14:09