Validation in struts can be done In two ways
1 manual or classic way
2 automated or declarative way
In the first approach we'll implement validate() method in ActionForm class.
Lets start step wise explanation, by following an Login Form example.
1 manual or classic way
2 automated or declarative way
In the first approach we'll implement validate() method in ActionForm class.
Lets start step wise explanation, by following an Login Form example.
Consider a page named login.jsp with following code
For the above jsp we have a ActionForm named LoginForm with default implementation of validate and reset method, code is as follows
We will not discus any LoginAction class which will be implementing the actual authorization logic because we will not be needing that in our current topic.
Validation in classic approach is done in 3 ways
Implement validate method in ActionForm class i.e. LoginForm in our case.
Write actual error messages in ApplicationResources.properties file
Turn on validation.
1 implementing validate method: validate method is implemented simply by using if-else statements as follows:
As you have noticed that return type of validate method is ActionErrors, so an object of type ActionErrors is created. By using if-else conditions we can store errors in ActionErrors object
Note the difference, in above statement errors is of type ActionErrors, and you are passing new object of type ActionError in parameters of add method.
You can think of ActionErrors object i.e. errors in our case as a map in which you are storing individual ActionError objects with the help of a key (first parameter in add method will act as a key.)
2 Writing actual error messages in ApplicationResources.properties file
A property files are used to store parameters which are stored in format of pair of strings, in which one string represent the name i.e. key and other represent value of that parameter.
Property file of our interest in this application is ApplicationResources.properties, which will be used to store actual error messages that will be shown on client browser.
Don't get confused once completed all flow will be clear, just continue reading.
so following is code of property file i am using in this particular example.
NOTE: one thing to be noted here is that keys to be used in property file should be same as the string passed to constructor of ActionError, while adding ActionError object.

3 Turning on validations: In order the validate method to be executed, we have to add an attribute to the mapping section of our ActionClass in struts-config.xml, which will be as follows :
if we don't set value of validate attribute to true in struts-config, control will be directly transferred to execute method of ActionClass after ActionForm is being populated. But if validate="true", then after populating ActionForm, RequestProcessor will invoke validate method. Validate method in turn will return ActionErrors object, if it is null then RequestProcessor will invoke execute method of ActionClass otherwise if ActionErrors is not null, then control is sent back to client including those error messages.
Displaying Error Messages on jsp
To display errors on your jsp write the following tag in jsp.
Above tag will print all the errors on the jsp.

And for displaying errors specifically in relative to input boxes use following tag syntax
In above tag property attribute refer to the key, we used to store ActionError object.
i.e.
so output will be like

Instead of <html:errors /> tag you can also use following tag
So that was about classic way of implementing validations in struts. but at this point your brain should raise hand asking How Do <html:errors />, <html:messages> tags find messages.
The reason behind this mystery is that struts stores ActionErrors object returned by validate method in request scope as following
By default, both tags that are <html:errors /> and <html:messages > uses this key to retrieve messages.
Now the question is can we use custom key
Answer is YES !!! we can
Suppose if we want to throw some message to jsp from ActionClass, in that case we will do it like
and on jsp
so the name attribute will be used to mention what to look for in request scope.
!(Ain't Mistake)
This is the section covering the mistakes I did or the errors I faced while giving this topic first try
Error 500: No input attribute for mapping path /login : This error generally comes when no value is specified for the input attribute of action elements in struts-config.xml.
Struts framework will forward the control to the path specified in input attribute if validation fails i.e. in case the validation in ActionForm class fails, control will not be passed to Action's execute method, rather control will be forwarded to the page specified in input attribute of specified action elements.
Second approach i.e. automated or declarative way coming in couple of days... cheers !!
<body>
<form action="login.do">
UserName : <input type="text" name="user">
Password : <input type="password" name="pwd">
<input type="submit" value="Login">
</body>
For the above jsp we have a ActionForm named LoginForm with default implementation of validate and reset method, code is as follows
public class LoginForm extends ActionForm
{
private String user = null;
private String pwd = null;
public String getUser() { return user; }
public String getPwd() { return pwd; }
public void setUser(String u) { this.user = u; }
public void setPwd(String p) { this.pwd = p; }
}
We will not discus any LoginAction class which will be implementing the actual authorization logic because we will not be needing that in our current topic.
Validation in classic approach is done in 3 ways
Implement validate method in ActionForm class i.e. LoginForm in our case.
Write actual error messages in ApplicationResources.properties file
Turn on validation.
1 implementing validate method: validate method is implemented simply by using if-else statements as follows:
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if(user==null||user.length()<4)
{
errors.add("user",new ActionError("login.user"));
}
if(pwd==null||pwd.length()<4)
{
errors.add("password",new ActionError("login.pwd"));
}
return errors;
}
As you have noticed that return type of validate method is ActionErrors, so an object of type ActionErrors is created. By using if-else conditions we can store errors in ActionErrors object
errors.add("user",new ActionError("login.user"));
Note the difference, in above statement errors is of type ActionErrors, and you are passing new object of type ActionError in parameters of add method.
You can think of ActionErrors object i.e. errors in our case as a map in which you are storing individual ActionError objects with the help of a key (first parameter in add method will act as a key.)
2 Writing actual error messages in ApplicationResources.properties file
A property files are used to store parameters which are stored in format of pair of strings, in which one string represent the name i.e. key and other represent value of that parameter.
Property file of our interest in this application is ApplicationResources.properties, which will be used to store actual error messages that will be shown on client browser.
Don't get confused once completed all flow will be clear, just continue reading.
so following is code of property file i am using in this particular example.
login.user=invalid username
login.pwd=invalid password
NOTE: one thing to be noted here is that keys to be used in property file should be same as the string passed to constructor of ActionError, while adding ActionError object.
3 Turning on validations: In order the validate method to be executed, we have to add an attribute to the mapping section of our ActionClass in struts-config.xml, which will be as follows :
<action-mappings>
<action name="loginForm" path="/login" scope="request"
type="net.mshome.firstsruts.actions.LoginAction"
validate="true"
input="./login.jsp" >
<forward name="success" path="./home.jsp"></forward>
<forward name="fail" path="./fail.jsp"></forward>
</action>
</action-mappings>
if we don't set value of validate attribute to true in struts-config, control will be directly transferred to execute method of ActionClass after ActionForm is being populated. But if validate="true", then after populating ActionForm, RequestProcessor will invoke validate method. Validate method in turn will return ActionErrors object, if it is null then RequestProcessor will invoke execute method of ActionClass otherwise if ActionErrors is not null, then control is sent back to client including those error messages.
Displaying Error Messages on jsp
To display errors on your jsp write the following tag in jsp.
<html:errors/>
Above tag will print all the errors on the jsp.
And for displaying errors specifically in relative to input boxes use following tag syntax
<html:errors property="user" /><br>
In above tag property attribute refer to the key, we used to store ActionError object.
i.e.
errors.add("user",new ActionError("login.user"));
so output will be like
Instead of <html:errors /> tag you can also use following tag
<html:messages id="msg" property="password">
<bean:write name="msg" />
</html:messages>
So that was about classic way of implementing validations in struts. but at this point your brain should raise hand asking How Do <html:errors />, <html:messages> tags find messages.
The reason behind this mystery is that struts stores ActionErrors object returned by validate method in request scope as following
request.setAttribute(Globals.ERROR_KEY,errors);
By default, both tags that are <html:errors /> and <html:messages > uses this key to retrieve messages.
Now the question is can we use custom key
Answer is YES !!! we can
Suppose if we want to throw some message to jsp from ActionClass, in that case we will do it like
if(<some condition>)
{
ActionErrors err= new ActionErrors();
err.add("FOLLOW", new ActionError("follow.blog"));
err.add("EMAIL", new ActionError("email.subscribe"));
request.setAttribute("CUSTOM_KEY", err);
}
and on jsp
<html:errors name="CUSTOM_KEY" />
so the name attribute will be used to mention what to look for in request scope.
!(Ain't Mistake)
This is the section covering the mistakes I did or the errors I faced while giving this topic first try
Error 500: No input attribute for mapping path /login : This error generally comes when no value is specified for the input attribute of action elements in struts-config.xml.
<action name="loginForm"
path="/login"
scope="request"
type="net.mshome.webapp.actions.LoginAction"
validate="true"
input="./input.jsp" >
<forward name="path1" path="./pass.jsp"></forward>
<forward name="path2" path="./fail.jsp"></forward>
</action>
Struts framework will forward the control to the path specified in input attribute if validation fails i.e. in case the validation in ActionForm class fails, control will not be passed to Action's execute method, rather control will be forwarded to the page specified in input attribute of specified action elements.
Second approach i.e. automated or declarative way coming in couple of days... cheers !!
0 nhận xét:
Đăng nhận xét