Post on 11-Nov-2015
description
Validations in strutsProcedure to performserver sidedeclarative form validations (using validator plug-in) with respect to our first Struts application:Step1: Configure validator plug-in in struts configuration file.In struts-config.xml
Step2: Keep validator-rules.xml file in WEB-INF folder by gathering that file from struts-core-1.3.8.jar file extraction.
Step3: Add properties file to WEB-INF/classes folder and configure that file in struts configuration file.
In struts-config.xml
Step4: Add default error messages of validator plug-in to the properties file.Note: Collect these error messages from the comments of validator-rules.xml file.
# Struts Validator Error Messageserrors.header=
errors.footer=
errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.
errors.maxlength={0} can not be greater than {1} characters.
errors.invalid={0} is invalid.
errors.byte={0} must be a byte.
errors.short={0} must be a short.
errors.integer={0} must be an integer.
errors.long={0} must be a long.
errors.float={0} must be a float.
errors.double={0} must be a double.
errors.date={0} is not a date.
errors.range={0} is not in the range {1} through {2}.
errors.creditcard={0} is an invalid credit card number.
errors.email={0} is an invalid e-mail address.
Step5: Make the formbean class of struts application extending from org.apache.struts.validator.ValidatorForm class.Note:
1) The regular pre-defined ActionForm class based form bean class can not work with validator plug-in.
2) validate(-,-) method of predefined ActionForm class cannot activate validator plug-in. Where as the validate(-,-) method of predefined ValidatorForm class can activate Validator plug-in.
3) Make sure that validate(-,-) method is not overridden in the formbean class because to call pre-defined validate() method of ValidatorForm class.
In struts-config.xml
Step6: Add validation.xml file in WEB-INF folder to apply the required validator rule on formbean class properties.
In validation.xml
mask
^[a-zA-Z]*$
mask
^[a-zA-Z]*$
Note: In the above file username, password formbean properties are configured with required, mask validator rule.
Step7: Add user defined messages in properties file as specified in validation.xml file to supply argument values of error messages.In MessageResources.properties
#user-defined messages to supply {n} values of above error messages
un.error=username
pwd.error=password
un.mask.error=please provide only alphabets for usernamepwd.mask.error=please provide only alphabets for Password#jsp label messages
name.username=UserName
pwd.password=Password
Step8: Configure input page for Action class.In struts-config.xml
Step9: Add tag in input jsp program.
Step10: Develop the remaining resources of struts application in regular manner.
Register.jsp
:
:
RegisterAction.javaimport org.apache.struts.action.*;
import org.apache.struts.validator.*;
import javax.servlet.http.*;
public class RegisterAction extends Action
{
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)throws Exception
{
DynaValidatorForm rf = (DynaValidatorForm)form;
String user=(String)rf.get("username");
String pass=(String)rf.get("password");
if(user.equals("bhaskar") && pass.equals("java"))
return mapping.findForward("ok");
else
return mapping.findForward("fail");
}
}
success.jsp
Login Successfull
failure.jsp
Login Failure
Try Again
Note: Add struts-extras.jar file to the project lib folder.Note: Test the application with the URL.
http://localhost:9999/webapp/register.jspCase1: On the browser
Now click on Register button without enter any data.
Now enter username as 4 and password as 5.
Now enter username as bhaskar and password as 5.
Now enter username as bhaskar and password as vbr.
Now click on Try Again link and enter username as bhaskar and password as java.
Procedure to performclient sidedeclarative form validations (using validator plug-in) with respect to our first Struts application:
Step1: Perform all the ten steps of previous class on struts apps.
Step2: Take form page as input page of Action class (register.jsp).
Step3: Add tag in the form page having form bean logical name.
Note: The above step generates one dynamic java script function having the JavaScript code of form validation logic (validator plug-in supply) that JavaScript function name notation is validate formbean logical name.
If formbean logical name is bean then the function name would be validateBean ().
For example if formbean logical name is abc then the function name could be validateAbc(). Call the above step generated dynamic JavaScript function against onsubmit event in tag of form page(see above).Note: Since validator plug-in performs both client side and server side form validations even though script code (JavaScript) is disabled through browser settings, the server side form validation logic takes place automatically.To disable script codes in browsers see the following link:http://www.niallp.pwp.blueyonder.co.uk/HelpTagsErrorsAndMessages.htmlhttp://www.enable-javascript.com/Procedure to performclient sideprogrammatic form validations with respect to our first Struts application:
Step1: Write java script code as shown below in the form page of Struts application (register.jsp).In register.jsp
function myValidate(frm)
{
//read form data
var unval=frm.username.value;
var pwdval=frm.password.value;
//write programatic client-side form validation logic
if(unval=="")
{
alert("username is required");
frm.username.focus();
return false;
}
else
{
var fchar=unval.charAt(0);
if(!isNaN(fchar))
{
alert("username must begin with alphabets");
frm.username.focus();
frm.username.value="";
return false;
}
}
if(pwdval=="")
{
alert("password is required");
frm.password.focus();
return false;
}
else
{
var fchar=pwdval.charAt(0);
if(!isNaN(fchar))
{
alert("password must begin with alphabet");
frm.password.focus();
frm.password.value="";
return false;
}
}
return true;
}//myValidate()
:
:
Step2: Develop the remaining resources.Procedure to performserver sideprogrammatic form validation with respect to our first Struts application:Note: For the above requirement we need to write the java code based form validation logic by overriding validate() method in our form bean class.
Step1: Prepare properties file having form validation error messages.WEB-INF /classes \ MessageResources.properties
MessageResources.properties errors.header=
errors.footer=#user-defined form validation error messages
un.req.error=Login username is required
pwd.req.error=Login password is required
un.alpha.error=Login username must be an alphabet
pwd.alpha.error=Login password must be an alphabet
#register.jsp label messages
name.username=UserName
pwd.password=Password
Note: In the above file keys & values are user definedStep2: Configure properties file in Struts-configuration file
In Struts-configuration.xml
Step3: Configure the form bean properties in struts configuration file.
Step4: Override validate () method in form bean class as shown below.In RegisterForm.javaimport org.apache.struts.action.*;
import org.apache.struts.validator.*;
import javax.servlet.http.*;
public class RegisterForm extends DynaValidatorForm{
public ActionErrors validate(ActionMapping mapping,HttpServletRequest request)
{
String username=(String)get("username");
String password=(String)get("password");
ActionErrors errors=new ActionErrors();
//write server side programatic form validation logic
if(username==null||username.equals("")||username.length()==0)
{
//for required rule
errors.add("unerr",new ActionMessage("un.req.error"));
}
else
{
//for firstchar name must be alphabet rule
char fchar=username.charAt(0);
if(!Character.isUpperCase(fchar)&&!Character.isLowerCase(fchar))
{
errors.add("unerr",new ActionMessage("un.alpha.error"));
}//if
}//else
if(password==null||password.equals("")||password.length()==0)
{
//for required rule
errors.add("pwderr",new ActionMessage("pwd.req.error"));
}
else
{
char fchar=password.charAt(0);
if(!Character.isUpperCase(fchar)&&!Character.isLowerCase(fchar))
{
errors.add("pwderr",new ActionMessage("pwd.alpha.error"));
}//if
}//else
return errors;
}
}
Step4: Configure input jsp page for Struts action class to display the form validation error messages (RegisterAction class).In Struts-configure.xml
Step5: Add tag in the input jsp program to decide the position of displaying from validation error messages.
In register.jsp:
:
:
Step5: Develop the remaining resources of Struts application like our first application.Resume Application
Struts validator framework exampleExample for server side validations1. Prototype:
2. PatientRegister.jsp
Registration Screen
3. Patient-config.xml(struts-config.xml)
4. Patient.xml(validation.xml)
mask
^[a-zA-Z]*$
minlength
10
min
20
max
100
datePattern
yyyy-MM-dd
mask
^\d{5,10}$
5. Patient.properties# Struts Validator Error Messages
errors.header=
errors.footer=
errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.
errors.maxlength={0} can not be greater than {1} characters.
errors.invalid={0} is invalid.
errors.byte={0} must be a byte.
errors.short={0} must be a short.
errors.integer={0} must be an integer.
errors.long={0} must be a long.
errors.float={0} must be a float.
errors.double={0} must be a double.
errors.date={0} is not a date.
errors.range={0} is not in the range {1} through {2}.
errors.creditcard={0} is an invalid credit card number.
errors.email={0} is an invalid e-mail address.
my.error.id=id
my.error.name=Name
my.error.address=Address
my.error.email=Email
my.error.age=Age
my.error.doj=Date of Joining
my.error.telephone=Telephone Number
my.error.mask.name=Please provide only alphabets for Name
my.error.mask.telephone=Please provide 5 (or) 10 integer digit Telephone Nomber
#RegisterPatient.jsp page labels
registration.id=Patient ID
registration.name=Patient Name
registration.email=E-Mail Address
registration.address=Resedential Address
registration.doj=Date of Joining (YYYY-MM-DD)
registration.age=Age
registration.telephone=Telephone Number
6. Web.xml
action
org.apache.struts.action.ActionServlet
application
Patient
config
/WEB-INF/patient-config.xml
1
action
*.do
Register.jsp
/tags/struts-html
/WEB-INF/struts-html.tld
/WEB-INF/struts-bean.tld
/WEB-INF/struts-bean.tld
7. PatientRegisterAction.javaimport javax.servlet.http.*;
import org.apache.struts.action.*;
import java.sql.*;
import org.apache.struts.validator.DynaValidatorForm;
public class PatientRegisterAction extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
{
Connection con = null;
PreparedStatement ps = null;
String status = null;
try
{
DynaValidatorForm b=(DynaValidatorForm)form;
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "admin");
ps = con.prepareStatement("INSERT INTO PATIENT VALUES(?,?,?,?,?,?,?)");
ps.setInt(1, Integer.parseInt((String)b.get("id")));
ps.setString(2, (String)b.get("name"));
ps.setString(3, (String)b.get("address"));
ps.setString(4, (String)b.get("email"));
ps.setDate(5, java.sql.Date.valueOf((String)b.get("doj")));
ps.setInt(6, new Integer((String)b.get("age")).intValue());
ps.setString(7, (String)b.get("telephone"));
status = null;
if(ps.executeUpdate() == 0)
status = "fail";
else
status = "ok";
}
catch(ClassNotFoundException ce)
{
ce.printStackTrace();
}
catch(SQLException se)
{
se.printStackTrace();
}
finally
{
try
{
if(ps != null)
ps.close();
}
catch(SQLException se)
{}
try
{
if(con != null)
con.close();
}
catch(SQLException se)
{}
}
return mapping.findForward(status);
} // execute()
} // class
8. Success.html
Registration Successful !!!
9. Failure.html
Registration Failure !!!
10. Test the application with the following URLhttp://localhost:9999/webapp/patientregister.jsp
Click on register button without enter the data.
Now enter the required data and click on Register button.
If the form bean class is developed by the programmer completely and totally then it is called as manual form bean class/explicitly form bean class. If framework software generates total formbean or at least formbean properties and their getXxx() and setXxx() methods dynamically. Then they are called as dynamic form beans.
Note: Programmatic form beans are good to use.Both DynaActionForm and DynaValidatorForm can generate form beans dynamically but DynaActionForm cant work with validator plug-in where as DynaValidatorForm can work with validator plug-in.
112