由於您沒有發佈任何代碼,我不確定您使用的驗證方法是什麼,或者您嘗試了什麼。以下是使用validate()
方法處理表單驗證的示例操作。
我原本忘記提及您需要更改表單,以便提交給「myAction!submit」而不僅僅是「myAction」。
public class MyAction extends ActionSupport {
/**
* Your profile, as loaded from the database.
*/
private Profile profile;
/**
* SkipValidation is required so that the validate() method is not invoked
* prior to the execute() method. Otherwise, all fields would be blank and
* we would end up showing validation errors on all fields.
*/
@SkipValidation
@Override
public String execute() throws Exception {
return INPUT;
}
@Override
public void validate() {
if (StringUtils.isEmpty(profile.getUsername())) {
addFieldError("profile.username", "User Name is required.");
}
// place any additional validations here...
// you can and should create convenience methods for performing validations.
}
public String submit() throws Exception {
// persist the changes and return an appropriate response
// e.g., redirect somewhere
return SUCCESS;
}
}
顯示動作和jsp。 – Quaternion 2011-03-07 14:58:26
您使用的是什麼Struts2驗證方法? 'validate()'方法或XML驅動驗證? – 2011-03-07 16:32:46