java 如何使用 GWT 编辑器框架进行验证?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4098579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:45:24  来源:igfitidea点击:

How to use the GWT editor framework for validation?

javagwteditoruibindergwt2

提问by Jan

I am trying to integrate with the new GWT Editor framework of GWT 2.1.0. I also want to add my validation checks into the framework. However, I am struggling to find a decent example how to do this.

我正在尝试与 GWT 2.1.0 的新 GWT 编辑器框架集成。我还想将我的验证检查添加到框架中。但是,我正在努力寻找如何做到这一点的体面示例。

For the moment I have the following code:

目前我有以下代码:

<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
    xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:e="urn:import:com.google.gwt.editor.ui.client">
    <ui:with type="be.credoc.iov.webapp.client.MessageConstants"
        field="msg" />
    <g:HTMLPanel>
        <e:ValueBoxEditorDecorator ui:field="personalReference">
            <e:valuebox>
                <g:TextBox />
            </e:valuebox>
        </e:ValueBoxEditorDecorator>
    </g:HTMLPanel>
</ui:UiBinder> 

And for my editor:

对于我的编辑器:

public class GarageEditor extends Composite implements Editor<Garage> {

    @UiField
    ValueBoxEditorDecorator<String> personalReference;

    interface GarageEditorUiBinder extends UiBinder<Widget, GarageEditor> {
    }

    private static GarageEditorUiBinder uiBinder = GWT.create(GarageEditorUiBinder.class);

    public GarageEditor() {
        initWidget(uiBinder.createAndBindUi(this));
    }

}

On what point do I have to call my validator and how do I integrate with it?

我必须在什么时候调用我的验证器以及如何与它集成?

Update:

更新:

I am actually looking for a way to retrieve a map with as key the property path, and as value the editor. There is a path field on a delegate, but this is not the path within the edited object, but the path in the editor class.

我实际上正在寻找一种方法来检索以属性路径为键并以编辑器为值的地图。委托上有一个路径字段,但这不是编辑对象内的路径,而是编辑器类中的路径。

Does anybody know if it is possible to do something like this?

有谁知道是否有可能做这样的事情?

采纳答案by Antonio

Annotate you beans with contstrants (see Person.java)

用contstrants注释你的bean(见Person.java

public class Person {
  @Size(min = 4)
  private String name;
}

Use the standard validation bootstrap to get a Validator on the client and validate your object (see ValidationView.java)

使用标准验证引导程序在客户端获取验证器并验证您的对象(请参阅ValidationView.java

Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Person>> violations = validator.validate(person);

Follow this pattern to create a Validator for the objects you want to validate on the client. (see SampleValidatorFactory.java)

按照此模式为要在客户端验证的对象创建验证器。(见SampleValidatorFactory.java

public final class SampleValidatorFactory extends AbstractGwtValidatorFactory {

  /**
   * Validator marker for the Validation Sample project. Only the classes listed
   * in the {@link GwtValidation} annotation can be validated.
   */
  @GwtValidation(value = Person.class,
      groups = {Default.class, ClientGroup.class})
  public interface GwtValidator extends Validator {
  }

  @Override
  public AbstractGwtValidator createValidator() {
    return GWT.create(GwtValidator.class);
  }
}

Include the module for your Validation Provider. Add replace-with tag in your gwt modle file telling GWT to use the Validator you just defined (see Validation.gwt.xml)

包括您的验证提供程序的模块。在您的 gwt 模型文件中添加替换标记,告诉 GWT 使用您刚刚定义的验证器(请参阅Validation.gwt.xml

<inherits name="org.hibernate.validator.HibernateValidator" />
<replace-with
    class="com.google.gwt.sample.validation.client.SampleValidatorFactory">
    <when-type-is class="javax.validation.ValidatorFactory" />
</replace-with>

Source

来源

回答by Jon Denly

I have done something similar to this by adding an additional DriverWrapper class that takes the existing Driver and Validator and adds a flush method that first delegates to the underlying Driver flush and then calls the Validator. Any errors returned are then added to the Editors using a new visitor, similar to the way the existing Flusher works. This means the existing decorators that display the errors next to the fields continue to work.

我通过添加一个额外的 DriverWrapper 类来完成与此类似的操作,该类采用现有的 Driver 和 Validator 并添加一个flush 方法,该方法首先委托底层驱动程序刷新然后调用验证程序。然后使用新访问者将返回的任何错误添加到编辑器中,类似于现有 Flusher 的工作方式。这意味着在字段旁边显示错误的现有装饰器继续工作。

/**
 * Wraps a Driver and provides validation using gwt-validation (JSR 303).
 * When calling flush, this will use the provided IValidator to validate the data
 * and use the InvalidConstraintValidationVisitor to add the errors to the delegates.
 * @see InvalidConstraintValidationVisitor
 * @param <T> the data type for the editor
 * @param <D> the driver type
 */
public class ValidationDriverWrapper<T extends IsValidatable<T>, D extends EditorDriver<T>> {
private IValidator<T> validator;
private D driver;

/**
 * Constructor, both parameters are required.
 * @param driver The driver to use to flush the underlying data.
 * @param validator The validator to use to validate the data.
 */
public ValidationDriverWrapper(D driver, IValidator<T> validator) {
    this.validator = validator;
    this.driver = driver;
}

/**
 * Flushes the underlying Driver and then calls the validation on the underlying Validator, cascading errors as EditorErrors
 * onto the delegates, using InvalidContraintValidationVisitor.
 */
public void flush()
{
    T data = driver.flush();
    Set<InvalidConstraint<T>> errors = validator.validate(data);
    Set<InvalidConstraint<T>> extraErrors = data.validate();
    if(extraErrors != null && !extraErrors.isEmpty())
    {
        errors.addAll(extraErrors);
    }
    driver.accept(new InvalidConstraintValidationVisitor<T>(errors));
}

回答by Jerome Cance

I've got exaclty the same problem.

我有同样的问题。

The documentation is not clear about it.

文档对此并不清楚。

What I'm currently doing is to recreate some widgets by extending them with widget I want to copy. After it I implement LeafValueEditor and HasEditorDelegate to override getValue().

我目前正在做的是通过使用我想要复制的小部件扩展它们来重新创建一些小部件。在它之后我实现 LeafValueEditor 和 HasEditorDelegate 来覆盖 getValue()。

In getValue(), use your validator and call if needed yourDelegate.recordError().

在 getValue() 中,使用验证器并在需要时调用 yourDelegate.recordError()。

Something like this: a little integer box which check that value is not greater than 10.

像这样:一个小整数框,检查该值不大于 10。

public class IntegerField extends ValueBox<Integer> implements LeafValueEditor<Integer>, HasEditorDelegate<Integer>
{
private EditorDelegate<Integer> delegate;

public IntegerField()
{
    super(Document.get().createTextInputElement(), IntegerRenderer.instance(), IntegerParser.instance());

    setStyleName("gwt-TextBox");

}

@Override
public Integer getValue()
{
    Integer value = super.getValue();

    if (value > 10)
    {
        delegate.recordError("too big integer !", value, null);
    }

    return value;
}

@Override
public void setValue(Integer value)
{
    super.setValue(value);
}

@Override
public void setDelegate(EditorDelegate<Integer> delegate)
{
    this.delegate = delegate;
}
}

The best approach is to simply add custom verification to existing widgets and not override them but I don't know how to do it !

最好的方法是简单地向现有小部件添加自定义验证,而不是覆盖它们,但我不知道该怎么做!

回答by Jon Vaughan

It's messy but to get the path of an Editor you could implement HasEditorDelegate (which will give you access to the delegate) and then cast the Delegate to AbstractEditorDelegate, which has a public String getPath() method.

这很麻烦,但是要获取编辑器的路径,您可以实现 HasEditorDelegate(这将使您可以访问委托),然后将委托转换为具有公共 String getPath() 方法的 AbstractEditorDelegate。

I don't think it is possible to do external validation though; validation happens in the editor at the point that a value is read from the field (see ValueBoxEditor - this editor uses getDelegate().recordError to raise an error). One option I did consider was to use the AbstractEditorDelegate access to call flushErrors(List) and to create that list of EditorErrors myself. To do that you need to know each of your field paths; hardcoding them is hardly desirable, but I don't see a way of looking up the Field by the edited property or anything like that.

不过,我认为不可能进行外部验证;在从字段中读取值时,在编辑器中进行验证(请参阅 ValueBoxEditor - 此编辑器使用 getDelegate().recordError 引发错误)。我确实考虑过的一种选择是使用 AbstractEditorDelegate 访问来调用 flushErrors(List) 并自己创建该 EditorErrors 列表。为此,您需要了解每个字段路径;硬编码它们几乎是不可取的,但我没有看到通过编辑的属性或类似的东西来查找字段的方法。

An alternative approach that might bear looking into is this submission for round trip validation using the requestfactory:

另一种可能值得研究的方法是使用 requestfactory 提交往返验证:

http://groups.google.com/group/google-web-toolkit-contributors/browse_thread/thread/5be0bda80547ca5a

http://groups.google.com/group/google-web-toolkit-contributors/browse_thread/thread/5be0bda80547ca5a

回答by Arthur Maltson

Validation doesn't exist in GWT yet, it's coming in the next release AFAIK. The current support for validation in GWT is server side JSR-303 and client side JSR-303 support is coming soon. Therefore, you'll have to do the validation manually. If you follow the MVP model, I think this validation logic would live in your Presenter.

GWT 中尚不存在验证,它将在下一版本 AFAIK 中提供。GWT 中当前对验证的支持是服务器端 JSR-303,客户端 JSR-303 支持即将推出。因此,您必须手动进行验证。如果您遵循 MVP 模型,我认为此验证逻辑将存在于您的 Presenter 中。