2012-01-13 26 views
0

模型如何工作?Wicket:類別上的綁定模型

我有一個Registry類是這樣的:

public class RegisterPanel extends Panel{ 

//empty user 
public User user = new User(); 

protected ServiceClient client = ((WicketApplication) (WicketApplication.get())).getClient(); 

@SuppressWarnings({ "rawtypes" }) 
public RegisterPanel(String id) { 
    super(id); 
    //creates form with an empty user 
    Form form = new RegisterForm("registerForm", user); 
    add(form); 
} 

@SuppressWarnings({ "rawtypes" }) 
class RegisterForm extends Form { 

    private String userId = ""; 
    private String email = ""; 
    private String password1 = ""; 
    private String password2 = ""; 

    private FormComponent formEmail; 
    private FormComponent formPassword1; 
    private FormComponent formPassword2; 

    @SuppressWarnings("unchecked") 
public RegisterForm(String id, User user) { 

    super(id); 
    add(new TextField("userId", new PropertyModel(this, "userId")).setRequired(true)); 
    formEmail = new TextField("email", new PropertyModel(this, "email")).setRequired(true); 
    formPassword1 = new PasswordTextField("password1", new PropertyModel(this, "password1")).setRequired(true); 
    formPassword2 = new PasswordTextField("password2", new PropertyModel(this, "password2")).setRequired(true); 
    add(formEmail); 
    add(formPassword1); 
    add(formPassword2); 
    } 

    @Override 
    public void onSubmit() { 

     Result result = client.register(email, userId, password1); 
     if(result.getStatus()) { 

         user.setEail(email); 
          user.setUserId(userId); 
          user.setPassword(password1); 
        client.postUser(user); 
     } 
    } 
} 
} 

但我怎麼配車型的工作?現在我只將PropertyModel綁定到我的TextFields。我以爲我可以綁定一個模型給我的空用戶,在提交方法上,我用我的模型而不是我的普通用戶。它是如何工作的?在模型上工作的優勢是什麼?

回答

1

使用模型有幾個好處:

public class RegisterPanel extends Panel{ 

protected ServiceClient client = ... 

public RegisterPanel(String id) { 
    super(id); 
    //creates form with an empty user 
    Form<Void> form = new RegisterForm<Void>("registerForm", new Model(new User())); 
    add(form); 
} 

class RegisterForm extends Form<Void> { 

    public RegisterForm(String id, IModel<User> user) { 
     super(id); 

     add(new TextField("userId", new PropertyModel(user, "userId")).setRequired(true)); 
     add(new TextField("email", new PropertyModel(user, "email")).setRequired(true); 
     add(new PasswordTextField("password", new PropertyModel(user, "password")).setRequired(true); 
     add(new PasswordTextField("password2", new Model("").setRequired(true); 
} 

    @Override 
    public void onSubmit() { 
     try { 
      client.registerAndPost(email, userId, password1); 
     } catch (ServiceException ex) { 
      ... 
     } 
    } 
} 

注:

  • RegisterForm不感興趣,其中用戶從
  • 表單字段來直接寫入用戶