Reputation: 73
For example I have an Action
class called UsersAction
where I have some methods like: login
, logout
, register
, and so on.
And I have written validate()
method as follows:
@Override
public void validate() {
if ("".equals(username)) {
addFieldError("username", getText("username.required"));
}
if ("".equals(email)) {
addFieldError("email", getText("email.required"));
} else if (!Utils.isValidEmail(email)) {
addFieldError("email", getText("invalid.email.address"));
}
if ("".equals(phone)) {
addFieldError("phone", getText("phone.required"));
}
if ("".equals(password)) {
addFieldError("password", getText("password.required"));
}
}
The problem is that this solution works only when register
action is called.
Anyway, it wont work on login
or logout
, because it will check if the fields aren't null
or email is correct, and always will give an error.
Okay, the solution for logout was to add @SkipValidation
annotation above it, but I don't know how to tell to it that login
have only 2 fields username
and password
, and it's not necessary to check email
and phone
too. I don't want to write an Action
class for each action in part, because the purpose of Struts 2 is not this.
Upvotes: 4
Views: 1578
Reputation: 1
Using annotations, annotate your action method login
with
@Action(value="login", results = {
@Result(name="input", location = "/login.jsp")
},interceptorRefs = @InterceptorRef(value="defaultStack", params = {"validation.validateAnnotatedMethodOnly", "true"}))
@Validations(requiredFields = {
@RequiredFieldValidator(type = ValidatorType.FIELD, fieldName = "username", message = "${getText("username.required")}"),
@RequiredFieldValidator(type = ValidatorType.FIELD, fieldName = "password", message = "${getText("password.required")}")
})
it will only validate username
and passsword
fields. Similar do the other action methods.
References:
Upvotes: 2
Reputation: 160181
Create validateMethodName
methods, where methodName
is the name of the method, e.g.,
validateLogin() { ... }
Otherwise provide some form of contextual information to your validate
method.
Upvotes: 6