Can classes that extend Struts2/XWork ValidatorSupport have state

118 views Asked by At

If you extend the ValidatorSupport class in Struts 2 can you have instance variables on the class? Can it have state or does it have to be stateless?

I know action classes aren't singletons and can have state but I'm not sure about their associated validators.

I need to know if I can have an instance variable within a validator that extends ValidatorSupport. For example:

public class SomeValidator extends ValidatorSupport {
    private boolean alreadyHasErrorOnPage;

}

If the validators are signlestons, using alreadyHasErrorOnPage since it would result in a race condition and never a consistent default state for each request/response. If they aren't singletons and a new SomeValidator instance is created for each request/response then using alreadyHasErrorOnPage would be safe.

Take the following with a grain of salt because I'm not sure how much of it is specifically related to the project I'm currently working on.

Validators are singles on our project. I went in and debugged the application and found instance members to not be at a default state after a second request/response. Essentially they carry over the value from the first or previous request/response.

The reason I'm still not sure is because our project seems to have wrapped and ValidatorSuppport and exposed an interface that our validators implement. Within our codebase there seems to be code that stores an instance of the validators in a map essentially making them singletons. I haven't been able to determine if stock struts2 behaves in the same manner.

1

There are 1 answers

5
Roman C On

They should have a state, because the state is the subject to validate, that should be set to the validator before it's executed. The validator instance should be built the same way like the actions in Struts2.

The object is passed to the Validator via the validate method. It has a signature

void validate(Object object) throws ValidationException;  

Generally the object is the action instance that you can validate in the method implementation. The validator instance is built via the validator factory. One is used the object factory to build the validator and inject it with container if there are available injectors. But the object factory, what ever implementation you use, just create a new instance and return it. So, each time you use the validator factory to build the validator the new instance is created. Then as you might seen the Validator has properties such as message, messageKey, messageParameters, etc. These properties define the state of the Validator. You can extend the ValidatorSupport with custom properties without fear. Because the new instance of the validator is created each time per validation, then it's thread safe.

Can it have state or does it have to be stateless?

It's already has a state, the stateless bean doesn't have public properties.