且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Struts验证无法正常工作

更新时间:2023-09-11 23:03:22

First, you don't need to return INPUT from validate, adding the fieldError will be enough to instruct the Workflow Interceptor to return INPUT automatically.

Second, the naming of your methods, actions and forms is overcomplicateed and potentially misleading... try keeping the things simpler for the future.

Third: you are doing the validation in the Action method. That's not how it works. The action method (by default execute(), but it can be anything, and you have named it validateForm()) must take care of the business of the Action, NOT of the validation. The validation is handled by (XML, Annotations or) a validate() method, that is called by the Validation Interceptor, and is executed before the action is reached. If the validation fails, the action method won't be executed, and the request will be redirected back to the result defined as INPUT.

Read more on the detailed flow if you are interested.

Then in your case:

public String validateForm() {        
    return SUCCESS;
}

public void validate() {
    if (name == null || name.equals("")) {
        addFieldError("name", "Name is required!");            
    }

    if (surname == null || surname.equals("")) {
        addFieldError("surname", "Surname is required!");
    }

    if (username == null || username.equals("")) {
        addFieldError("username", "Username is required!");
    }

    if (password == null || password.equals("")) {
        addFieldError("password", "Password is required!");
    }

    if (!passwordCheck.equals(password)) {
        addFieldError("password", "Passwords do not match!");
        addFieldError("passwordCheck", "");
    } 
}

But please change that methods / actions names ASAP, for your own safety :)

相关阅读

推荐文章