我们可以创建一个可以在GWT中的客户端和服务器之间共享的验证类(或设计某种结构)吗?



这是我的 Gwt 问题。比如说,我收到一个表格,上面有电子邮件、名字、用户名、密码......文本框和提交按钮。当用户单击"提交"时,客户端将验证所有字段,在所有字段正常后,它们将被发送到服务器进行另一个完全相同的验证。

有人建议我创建一个实用程序类并将该类放入共享包中。

看看这个代码

在 my.com.client 包中:

import my.com.shared.Utility;    
public class CustPresenter extends
    Presenter<CustPresenter.MyView, CustPresenter.MyProxy> {

  @Inject DispatchAsync dispatchAsync;

  public void postData(){
     PostData postDataAction=new PostData();
     String fName=fNameTextBox.getText();
     String lName=lNameTextBox.getText();
     //....... more field here ....//
     if(!Utility.isOKString(fName)){
        MyDialogBox myD=new MyDialogBox(fName, "Not OK");
     }
     else if (!Utility.isOKString(lName)){
        MyDialogBox myD=new MyDialogBox(lName, "Not OK");
     }
     ///.......more checking here//
    postDataAction.setFName(fName);
    postDataAction.setFName(lName);
    //... more setting here...// 
     dispatchAsync.execute(postDataAction, postDataCallback);
 }
 private AsyncCallback<PostDataResult> postDataCallback=new AsyncCallback<PostDataResult>(){
    @Override
    public void onFailure(Throwable caught) {
    }
    @Override
    public void onSuccess(PostDataResult result) {
         String resultStr=result.getResult();
         if(resultStr.equals("fName is not OK")){
             MyDialogBox myD=new MyDialogBox(fName, "Not OK");
         }
         else if (resultStr.equals("lName is not OK")){
             MyDialogBox myD=new MyDialogBox(lName, "Not OK");
         }
         /// more displaying err message...
    }
   };
}

在 my.com.server 包中

import my.com.shared.Utility;
public class PostDataActionHandler implements
        ActionHandler<PostData, PostDataResult> {
    @Override
    public PostDataResult execute(PostData action, ExecutionContext context)
            throws ActionException {
        String fName=action.getFName();
        String lName=action.getLName();
        //more geting here....//
        String resultInfo="";
        if(!Utility.isOKString(fName)){
              resultInfo="fName is not OK";
        }
        else if (!Utility.isOKString(lName)){
              resultInfo="lName is not OK";
        }
       ////... more checking here///
        else{
            postData();
        }
        return new PostDataResult(resultInfo);
    }
}

正如您在此结构中看到的,即使我在共享包中使用了实用程序,我仍然需要验证相同的数据 3 次。而且有很多重复项。

所以我的问题是:

我们可以创建一个特定的验证类(或设计某个结构)并将该类放在共享包中,以便客户端和服务器可以使用它,所以我只需要验证 1 次而不是像这样做 3 次?

>GWT通过注释支持JSR-303 Bean验证,并且相同的验证可以在客户端和服务器端使用。请参阅 GWT 文档的验证部分。

最新更新