Why we cannot change anything in validate method In Struts2?

1.1k views Asked by At

In Struts2 validate method is called before execute method. But why we cannot change any field value in validate method?

2

There are 2 answers

4
Ashutosh Ranjan On

I strongly agree with @jon Skeet, a validate() method is meant to do validation only.

But to answer @prtk_shah's question i would like to add that if you are using validate() method of ActionSupport class, you can change field value in validate method using the following example:

public class LoginAction extends ActionSupport{
private String userName;
private String password;
//getter setter
@Override
    public void validate() {
        super.validate();
        if(getUserName()==null){
            setUserName("abc");
        }

    }
}

By default, validate() method will return the "input" string, but if the result is mapped to the "input" in struts.xml, then you can get your field value in welcome.jsp by using this code:

<s:property value="userName"/>

Note: The above example can be used to achieve what you have asked in the question, but validate() method is used for validation purpose only.

2
Jon Skeet On

Any particular method should do one thing. A validate() method should validate data - it should check whether it's correct, not try to fix it up. The result of validation should simply be a pass or a fail; if it does anything else, it's doing too much.

(This isn't specific to Struts at all - it's the general meaning of validation, IMO.)