struts2编辑页面验证?

时间:2011-03-07 10:20:16

标签: validation struts2

我有一个包含用户个人资料的表格,下面我给出了一个按钮(编辑个人资料),用户可通过该按钮更新他/她的个人资料,当用户点击编辑个人资料时,将显示一个新页面其中包含用户的所有信息,并从数据库中填充。

我面临的问题是此页面中没有进行验证,例如用户删除了他的用户名并尝试更新他应该显示的个人资料*用户名是必需的 而不是它抛出一些错误,我填写验证没有发生在这里,因为数据来自数据库,但我不确定,任何人都可以帮助我。

1 个答案:

答案 0 :(得分:0)

由于您没有发布任何代码,我不确定您使用的验证方法或尝试的方法。以下是使用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;
    }
}
相关问题