Struts framework provides property files functionality with internationalization
(I18N) features. These message resources can be configured in Struts configuration
file by adding the below xml.
This configuration in config file and the related property file(MessageResources.properties)
is already there in blank Struts war file. The message resource is at
location <Tomcat-Home>\webapps\salsa-tutorial\WEB-INF\classes\MessageResources.properties
Open MessageResources.properties and add the following lines to define
the error messages used in validate() method.
login.userName.error=Invalid user name
login.password.error=Invalid password
Complete listing of LoginForm.java
package com.salsa;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;
import javax.servlet.http.HttpServletRequest;
public class LoginForm extends ActionForm {
private String userName;
private String password;
public String getuserName() {
System.out.println("LoginForm::getuserName()");
return userName;
}
public void setuserName(String user) {
userName = user;
System.out.println("LoginForm::setuserName()");
}
public String getPassword() {
return password;
}
public void setPassword(String passWord) {
password = passWord;
}
public void reset(ActionMapping mapping,
HttpServletRequest request) {
System.out.println("LoginForm::reset()");
userName=null;
password=null;
}
public ActionErrors validate(
ActionMapping mapping,
HttpServletRequest request) {
System.out.println("LoginForm::validate()");
ActionErrors errors = new ActionErrors();
if (userName==null || userName.trim().equals("")){
errors.add("userName", new ActionMessage("login.userName.error"));
}
if (password==null || password.trim().equals("")){
errors.add("password", new ActionMessage("login.password.error"));
}
return errors;
}
}
Create an alias for this form bean in within <form-beans> tag of
struts-config.xml
Submit and Cancel Button configurations in the Struts Config file are
highlighted below
<action path="/loginAction"
type="com.salsa.UserLoginAction"
name="userLoginForm"
input="/loginForm.jsp"
cancellable="true">
<forward name="loginsuccess" path="/loginStatus.jsp"
/>
<forward name="logincancel" path="/loginCancel.jsp"
/>
</action>
If you do not set cancellable="true" in action mapping, InvalidCancelException
will be thrown
And finally create the JSP files to display successful logins and cancelled
logins. This login is incomplete without validating the user with the
database values for login and password. We will complete the database
part in our database section.
Login status uses a Struts tag library struts-bean(tags-bean) to display
messages from MessageResources.properties. Add The key login.status
in the property file.