Try to create a user with invalid values. For example an invalid email address that does not follow email addresses rules. You will see that the system does not check the validity of the data and the user still gets inserted into the database.
To solve this issue,we need to validate the data before inserting into the database or perform any operation on the data. We have two options to do this.
1. Perform the validation in action class and return to failure if the validation fails.
2. Perform validation in form bean.
The first option is not feasible because one form bean may be used in many actions. So we will need to perform validation in all actions where this form bean is used. The better choice is to perform validation in form bean.
Struts framework provides validation facility for form beans. If we need to perform validation on a form bean,we need to override validate method in our ActionForm class. The validate method returns an instance of ActionErrors. We can return ActionErrors instance with appropriate ActionError object if the validation fails,or simply return empty ActionErrors instance to indicate that the validation has passed and the struts frame may forward the request to action class. Let’s add the validation to our User class.
public ActionErrors validate( ActionMapping mapping,HttpServletRequest request ) { ActionErrors errors = new ActionErrors(); if( getUserId().length()<1 ) { errors.add("name",new ActionMessage("null.check","User ID")); } if(getEmail().length()>0) { { //Yes! user entered email address. validate it if(!getEmail().matches("^[a-zA-Z][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$")){ errors.add("name",new ActionMessage("email.invalid")); } } return errors; }
Also we need to enable the validate=”true” and provide an input attribute in the action configuration in struts-config.xml
<action attribute="loginForm" name="loginForm" path="/adduser" scope="request" validate="true" input="/adduser.jsp" type="com.visualbuilder.struts.action.AddUserAction"> <forward name="success" path="/manageusers.do" /> </action>
Also we have used two error messages if the validation fails. Add these two keys in the ApplicationResources.properties.
null.check = {0} cannot be null or empty email.invalid = Email address does not pass the validation rules
Now run the application and try to create a user with empty User ID or invalid email address. You will see the system does not insert the user into the database.
|