I have a login.jsp
page in my application. I'm using Struts 2 and a simple validate()
method to validate my form. I have two questions:
validate()
method in my form bean class validates the form. I.e checks for empty fields etc. If I need to check my username and password combination should I do this inside validate()
or in my action class?
If I am doing the same in my Action
class, correct combination leads to success page. I want the incorrect combination to lead to my JSP page along with the error message: "Incorrect combination". How can I check in my JSP page that the request has come from action class so that it can print the error message "Incorrect combination"?
Authentication belongs in the action, not in validation, IMO.
I might consider using XML or annotation validations for the fields themselves and put the login attempt in validate()
, but the code is small, and I'd be pretty comfortable with it either way.
public String execute() {
if (userService.loginValid(username, password) {
return SUCCESS;
}
addActionError(getText("login.failure"));
return FAILURE;
}
I would use the framework's support for action-level error messages rather than using a flag (and I wouldn't duplicate that flag with a local if I did), and I strongly recommend using something you can inject to do the actual logging in to make testing easier.
Using the validate()
approach makes things pretty tight:
public void validate() {
if (!userService.loginValid(username, password)) {
addActionError(getText("login.failure"));
}
}
Assuming you define reasonable "input" and "success" results that might be all you need. If developers looking at the code are familiar with the framework the validate()
version is relatively clear.
If you're not interested in using XML or annotation validations, you can do that manually as well. That definitely belongs in validate()
, and for common utility methods like this, static imports make the code still relatively concise:
public void validate() {
boolean tryLogin = true;
if (isBlank(username)) {
addFieldError("username", getText("login.username.required"));
tryLogin = false;
}
if (isBlank(password)) {
addFieldError("password", getText("login.password.required"));
tryLogin = false;
}
if (tryLogin && !userService.loginValid(username, password)) {
addActionError(getText("login.failure"));
}
}
(I added the tryLogin
flag to avoid seeing the error message for a login that will obviously fail, although this could be handled in other ways as well. Post-login processing elided.)