该模型如何运作?
我有一个像这样的注册表类:
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);
}
}
}
}
但我如何使用模型?现在我将PropertyModels绑定到我的TextFields。我以为我可以将模型绑定到我的空用户,而在提交方法上,我在我的模型上工作,而不是在我的普通用户上。它是如何工作的?什么是在模型上工作的优势?
答案 0 :(得分: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) {
...
}
}
}
注意: