Converters, Listeners and Validators in Java EE 7 – Java EE 7中的转换器、监听器和验证器

最后修改: 2017年 4月 14日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Java Enterprise Edition (JEE) 7 provides some useful features e.g. for validating user input, converting values into appropriate Java data types.

Java企业版(JEE)7提供了一些有用的功能,例如验证用户输入,将数值转换为适当的Java数据类型。

In this tutorial, we’ll focus on those features provided by converters, listeners, and validators.

在本教程中,我们将重点讨论由转换器、监听器和验证器提供的那些功能。

2. Converters

2.转换器[/strong

A converter allows us to transform string input values into a Java data types. Predefined converters are located in the javax.faces.convert package, and they are compatible with any Java data type or even standard classes like Date.

转换器允许我们将字符串输入值转换为一个Java数据类型。预定义的转换器位于javax.faces.convert包中,它们与任何Java数据类型甚至是标准类(如Date.)兼容。

To define an Integer converter, first we create our property in the managed bean used as a back end of our JSF form:

为了定义一个Integer转换器,首先我们在作为JSF表单后端的托管Bean中创建我们的属性。

private Integer age;
	 
// getters and setters

Then we create the component in our form using the f:converter tag:

然后我们使用f:转换器标签在我们的表单中创建该组件。

<h:outputLabel value="Age:"/>
<h:inputText id="Age" value="#{convListVal.age}">
    <f:converter converterId="javax.faces.Integer" />
</h:inputText>
<h:message for="Age" />

In a similar way, we create the other numeric converters like the Double converter:

以类似的方式,我们创建其他数字转换器,如Double转换器。

private Double average;

Then we create the appropriate JSF component in our view. Please note that we are using the variable average, which is then mapped to the field using the getter and the setter by name convention:

然后我们在我们的视图中创建适当的JSF组件。请注意,我们使用的是变量average,,然后使用getter和setter的名称惯例将其映射到字段。

<h:outputLabel value="Average:"/>
<h:inputText id="Average" value="#{convListVal.average}">
    <f:converter converterId="javax.faces.Double" />
</h:inputText>
<h:message for="Average" />

If we want to give the feedback to the user, we need to include an h:message tag to be used by the control as a placeholder for error messages.

如果我们想向用户提供反馈,我们需要包括一个h:message标签,作为错误信息的占位符,由控件使用。

A useful converter is the DateTime converter because it allows us to validate dates, times and format these values.

一个有用的转换器是DateTime转换器,因为它允许我们验证日期、时间和格式化这些值。

First, as in previous converters, we declare our field with the getters and setters:

首先,和以前的转换器一样,我们用getters和setters声明我们的字段。

private Date myDate;
// getters and setters

Then we create the component in our view. Here we need to enter the date using the pattern, if the pattern is not used then we get an error with an example of a correct pattern of the input:

然后我们在我们的视图中创建组件。在这里,我们需要使用模式来输入日期,如果没有使用模式,那么我们就会得到一个错误,其中有一个正确的输入模式的例子。

<h:outputLabel value="Date:"/>
<h:inputText id="MyDate" value="#{convListVal.myDate}">
    <f:convertDateTime pattern="dd/MM/yyyy" />
</h:inputText>
<h:message for="MyDate" />
<h:outputText value="#{convListVal.myDate}">
    <f:convertDateTime dateStyle="full" locale="en"/>
</h:outputText>

In our case, we can convert our input date and send the post data, formatted as a full date in our h:outputText.

在我们的案例中,我们可以转换我们的输入日期,并在我们的h:outputText.中发送格式化为完整日期的帖子数据。

3. Listeners

3.听众

A listener allows us to monitor changes in our components; we are monitoring when the value of a text field changes.

监听器允许我们监测我们的组件的变化;我们正在监测一个文本字段的值何时发生变化。

As before we define the properties in our managed bean:

和以前一样,我们在我们的托管Bean中定义了这些属性。

private String name;

Then we define our listener in the view:

然后我们在视图中定义我们的监听器。

<h:outputLabel value="Name:"/>
<h:inputText id="name" size="30" value="#{convListVal.name}">
    <f:valueChangeListener type="com.baeldung.convListVal.MyListener" />
</h:inputText>

We set our h:inputText tag by adding an f:valueChangeListener and also, inside the listener tag, we need to specify a class, which will be used to perform the tasks when the listener is triggered.

我们通过添加一个f:valueChangeListener来设置我们的h:inputText标签,同时,在监听器标签内,我们需要指定一个类,当监听器被触发时,它将被用于执行任务。

public class MyListener implements ValueChangeListener {
    private static final Logger LOG = Logger.getLogger(MyListener.class.getName());	
        
    @Override
    public void processValueChange(ValueChangeEvent event)
      throws AbortProcessingException {
        if (event.getNewValue() != null) {
            LOG.log(Level.INFO, "\tNew Value:{0}", event.getNewValue());
        }
    }
}

The listener class must implement the ValueChangeListener interface and override the processValueChange() method to do the listener tasks, to write a log message.

监听器类必须实现ValueChangeListener 接口,并重写processValueChange()方法,以完成监听器的任务,写一条日志信息。

4. Validators

4.验证人

We use a validator to validate a JSF component data, with a set of standard classes provided, to validate the user input.

我们使用一个验证器来验证JSF组件的数据,提供一组标准的类,来验证用户的输入。

Here, we defined a standard validator to enable us to check the length of a user input in a text field.

在这里,我们定义了一个标准的验证器,使我们能够检查用户在一个文本字段中输入的长度。

First, we create our field in the managed bean:

首先,我们在托管Bean中创建我们的字段。

private String surname;

Then we create our component in the view:

然后我们在视图中创建我们的组件。

<h:outputLabel value="surname" for="surname"/>
<h:panelGroup>
    <h:inputText id="surname" value="#{convListVal.surname}">
        <f:validateLength minimum="5" maximum="10"/>
    </h:inputText>
    <h:message for="surname" errorStyle="color:red"  />
</h:panelGroup>

Inside the h:inputText tag we put our validator, to validate the length of the input. Please remember that there are various standard validators predefined in JSF and we can use them in a similar way to the one presented here.

h:inputText标签内,我们放置了我们的验证器,以验证输入的长度。请记住,在JSF中预定义了各种标准的验证器,我们可以用与这里类似的方式来使用它们。

5. Tests

5.测试

To test this JSF application, we are going to use Arquillian to perform a functional testing with Drone, Graphene and Selenium Web Driver.

为了测试这个JSF应用程序,我们将使用Arquillian与Drone、Graphene和Selenium Web Driver进行功能测试。

First, we deploy our application using ShrinkWrap:

首先,我们使用ShrinkWrap:部署我们的应用程序。

@Deployment(testable = false)
public static WebArchive createDeployment() {
    return (ShrinkWrap.create(
      WebArchive.class, "jee7.war").
      addClasses(ConvListVal.class, MyListener.class)).
      addAsWebResource(new File(WEBAPP_SRC, "ConvListVal.xhtml")).
      addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}

Then we test the error messages of each component to verify that our application is working properly:

然后我们测试每个组件的错误信息,以验证我们的应用程序是否正常工作。

@Test
@RunAsClient
public void givenAge_whenAgeInvalid_thenErrorMessage() throws Exception {
    browser.get(deploymentUrl.toExternalForm() + "ConvListVal.jsf");
    ageInput.sendKeys("stringage");
    guardHttp(sendButton).click();
    assertTrue("Show Age error message",
      browser.findElements(By.id("myForm:ageError")).size() > 0);
}

Similar tests are performed on each component.

对每个部件都要进行类似的测试。

6. Summary

6.总结

In this tutorial, we created implementations of converters, listeners, and validators provided by JEE7.

在本教程中,我们创建了由JEE7提供的转换器、监听器和验证器的实现。

You can find the code from the article over on Github.

你可以从Github上的文章中找到代码