Struts 1 :Types of Validation - DynaValidatorForm , validation.xml , validator-rules.xml , validate( ) Commons Validator API , ActionClass validation , UI Tags , etc.

I assume you folks have a working experience with Struts in general , i.e the syntaxes , conventions,etc. So I would straight away start off the Validation Framework commonly used with Struts.

1. Using the "org.apache.struts.validator.DynaValidatorForm"

DynaActionForm is specialized subclass of ActionForm that allows the
creation of form beans with dynamic sets of properties, without requiring the
developer to create a Java class for each type of form bean.

DynaActionForm eliminates the need of FormBean class and now the form bean
definition can be written into the struts-config.xml file. So, it makes the
FormBean declarative and this helps the programmer to reduce the development time.

Entry at the Struts-Config.xml

<form-beans>
	<form-bean name="ApplicationBasicInfoBean"
type="org.apache.struts.validator.DynaValidatorForm">
	<form-property name="userLName" type="java.lang.String" />
	<form-property name="userGender" type="java.lang.String" />
	<form-property name="userPhoneNumber" type="java.lang.String" />
	<form-property name="userAge" type="java.lang.String" />
	<form-property name="userFName" type="java.lang.String" />
	</form-bean>
....
</form-beans>

DynaForm saves us the effort to declare ActionForm bean explicitly.Moreover,The DynaValidatorForm validates form properties based on rules in XML and works best if you have a lot of "simple" rules, which is why it can reduce your own code.

Entry for Struts-Config.xml continued...Declaring the plugin

<!-- Validator Definitions -->
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
	<set-property property="pathnames"
	value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml" />
</plug-in>

Entry at the validation.xml

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!--  Validation #2 : Validation against DynaActionFormBean  -->
<form-validation>
<formset>
<form name="ApplicationBasicInfoBean">
	<field property="userFName" depends="required">
		<msg name="required" key="error.NonEmptyFNameMsg.key" />
	</field>
	<field property="userLName" depends="required">
	        <msg name="required" key="error.NonEmptyLNameMsg.key" />
	</field>
	<field property="userPhoneNumber" depends="required,integer">
		<msg name="required" key="error.NonEmptyPhoneNumbrMsg.key" />
		<msg name="integer" key="error.NonNumericPhNumberMsg.key" />
	</field>
</form>
</formset>
</form-validation>

The "key" entries are mapped to the "ApplicationResources_en.properties"

The "message-resources" entry from Struts-Config.xml"

<message-resources parameter="com.Struts.POC.
	ApplicationResources.ApplicationResources_de" />
<message-resources parameter="com.Struts.POC.
	ApplicationResources.ApplicationResources_fr" />
<message-resources parameter="com.Struts.POC.
	ApplicationResources.ApplicationResources_en" />
<message-resources parameter="com.Struts.POC.
	ApplicationResources.ApplicationResources" />

The "message-resources" file for English contains the Keys corresponding to the Error Keys set in the Validation.xml :

error.NonNumericPhNumberMsg.key=
	Please enter a numeric Phone Number.
error.NonEmptyFNameMsg.key=
	First Name is required.
error.NonEmptyLNameMsg.key=
	Last Name is required.
error.NonEmptyPhoneNumbrMsg.key=
	Phone Number is required.
error.NonEmptyGenericMsg.key=
	The field {0},{1},{2} and {3} cannot be empty.


2. Extending the "ActionForm" - The classical way.

Entry at the Struts-Config.xml

<form-beans>
<form-bean name="ApplicationBasicInfoBean"
	type="org.apache.struts.validator.DynaValidatorForm">
	<form-property name="userLName" type="java.lang.String" />
	<form-property name="userGender" type="java.lang.String" />
	<form-property name="userPhoneNumber" type="java.lang.String" />
	<form-property name="userAge" type="java.lang.String" />
	<form-property name="userFName" type="java.lang.String" />
	</form-bean>
	
<form-bean name="ApplicationAdvancedInfoBean" 
	type="com.Struts.POC.ApplicationBeans.
              ApplicationAdvancedInfoBean" />

</form-beans>

A simple Form Bean from the classical Struts examples.

The ApplicationAdvancedInfoBean.java

public class ApplicationAdvancedInfoBean extends ActionForm{

	private static final long serialVersionUID = 1L;
	
	public String userYrsOfExp;
	public String userYrsOfRelExp;
	public String userPANNumber;
	public String userYrOfPassOut;
	public String userDegreeType;
	public String userPercentage;
	public String userDomainType;
	public String userTechnicalType;
	public String userExpertLevel;
	
	public String getUserYrsOfExp() {
		return userYrsOfExp;
	}
	public void setUserYrsOfExp(String userYrsOfExp) {
		this.userYrsOfExp = userYrsOfExp;
	}
	public String getUserYrsOfRelExp() {
		return userYrsOfRelExp;
	}
	public void setUserYrsOfRelExp(String userYrsOfRelExp) {
		this.userYrsOfRelExp = userYrsOfRelExp;
	}
	public String getUserPANNumber() {
		return userPANNumber;
	}
	public void setUserPANNumber(String userPANNumber) {
		this.userPANNumber = userPANNumber;
	}
	public String getUserYrOfPassOut() {
		return userYrOfPassOut;
	}
	public void setUserYrOfPassOut(String userYrOfPassOut) {
		this.userYrOfPassOut = userYrOfPassOut;
	}
	public String getUserDegreeType() {
		return userDegreeType;
	}
	public void setUserDegreeType(String userDegreeType) {
		this.userDegreeType = userDegreeType;
	}
	public String getUserPercentage() {
		return userPercentage;
	}
	public void setUserPercentage(String userPercentage) {
		this.userPercentage = userPercentage;
	}
	public String getUserDomainType() {
		return userDomainType;
	}
	public void setUserDomainType(String userDomainType) {
		this.userDomainType = userDomainType;
	}
	public String getUserTechnicalType() {
		return userTechnicalType;
	}
	public void setUserTechnicalType(String userTechnicalType) {
		this.userTechnicalType = userTechnicalType;
	}
	public String getUserExpertLevel() {
		return userExpertLevel;
	}
	public void setUserExpertLevel(String userExpertLevel) {
		this.userExpertLevel = userExpertLevel;
	}
	
	@Override
	public ActionErrors validate(ActionMapping mapping,
			HttpServletRequest request) {
		ActionErrors actionErrors = new ActionErrors();
		
	if((userPANNumber==null)||(userPANNumber.equals("")))
		actionErrors.add("errors.userPANNumber", 
		new ActionMessage("PAN Card details is required"));
	if((Integer.parseInt(userYrsOfExp)<(Integer.parseInt(userYrsOfRelExp))))		
		actionErrors.add("errors.userExpError", 
		new ActionMessage("User Experince should be equal or 
		more than Relevant Experience"));
	
	return actionErrors;
	}
	
	@Override
	public void reset(ActionMapping mapping, HttpServletRequest request) {
		// TODO Auto-generated method stub
		super.reset(mapping, request);
	}
}

The JSP Page

<tr align="left">
	<td nowrap><b>PAN Card Number : </b></td>
	<td><html:text property="userPANNumber" size="30" maxlength="30"
				style="width:200px;" /> </td>
	<td><html:errors property="userPANNumber" /></td>
</tr>

If the validation results in an Error,the corresponding Error message would be displayed adjacent to the Input block as shown.

3. Validation within ActionClass

public class EnterPersonalDetailsAS extends org.apache.struts.action.Action {

public ActionForward execute(ActionMapping mapping, ActionForm form,
 HttpServletRequest request, HttpServletResponse response) throws Exception {

...............

flag=UserInputCheckUtils.PureNumberCheck(PhoneNumber);
ActionErrors vActionErrors = new ActionErrors();
ActionMessages messages = new ActionMessages();
if(flag==false)
   {
    //The Bean property is mapped : 
    //vActionErrors.add(<Bean Property>, new ActionError(<Message Key>));
    vActionErrors.add("userPhoneNumber", 
	new ActionError("error.NonNumericPhNumberMsg.key"));
    forward=mapping.findForward("BackToEnterPersonalDetails");
   }

   if (!vActionErrors.isEmpty()) {
	saveErrors(request, vActionErrors);			
	}
	if (!messages.isEmpty()) {
	saveMessages(request, messages);
	}
.........

The mapping of the Error Keys is same as that of all other validations.


A word about the Struts "ActionErrors" class

Struts' ActionErrors class comes in handy in resolving the first issue of stacking messages of different categories. To display the error messages of different categories, define these categories such as FATAL, ERROR, WARNING, or INFO, in an interface. Then, in the Action or form-bean class, you can use:
The Controller in the Struts application can carryout normal checks as :

errors.add("fatal", new ActionError("....")); or 
errors.add("error", new ActionError("....")); or 
errors.add("warning", new ActionError("....")); or 
errors.add("information", new ActionError("....")); 
saveErrors(request,errors);

WAYS TO DISPLAY ERROR MESSAGES ON JSP:

If we intend to display all Errors contained in the REQUEST scope:

<html:errors/>

If we intend to display Errors specific to an HTML Entry:

<tr align="left">
	<td nowrap>
	<bean:message key="label.UserInput.key" arg0="First Name"/></td>
	<td>
	<html:text property="userFName" size="20" styleClass="field"
		maxlength="10" style="width:200px;" /> </td>
	<td>
	<html:errors property="userFName" /></td>
</tr>

Displaying all Messages in the REQUEST Scope :GLOBAL_ERROR using
logic:messagesPresent

<logic:messagesPresent property="org.apache.struts.action.GLOBAL_ERROR">
<font color="red">
	<ul>
	<html:messages property="org.apache.struts.action.GLOBAL_ERROR"
			id="message">
		<li><bean:write name="message" /><br>
	</html:messages>
	</ul>
	</font>
</logic:messagesPresent>

UI TAGS USED :

<%@ taglib uri="/WEB-INF/struts-html" prefix="html"%>
<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<%@ taglib uri="/WEB-INF/struts-logic" prefix="logic"%>

Bean

· This tag library contains tags useful in accessing beans and their properties, as well as defining new beans (based on these accesses) that are accessible to the remainder of the page via scripting variables and page scope attributes. Convenient mechanisms to create new beans based on the value of request cookies, headers, and parameters are also provided.
· Many of the tags in this tag library will throw a JspException at runtime when they are utilized incorrectly (such as when you specify an invalid combination of tag attributes). JSP allows you to declare an "error page" in the <%@ page %> directive. If you wish to process the actual exception that caused the problem, it is passed to the error page as a request attribute under key org.apache.struts.action.EXCEPTION.
·

Html:

· This taglib contains tags used to create struts input forms, as well as other tags generally useful in the creation of HTML-based user interfaces. Many of the tags in this tag library will throw a JspException at runtime when they are utilized incorrectly (such as when you specify an invalid combination of tag attributes).
· JSP allows you to declare an "error page" in the <%@ page %> directive. If you wish to process the actual exception that caused the problem, it is passed to the error page as a request attribute under key org.apache.struts.action.EXCEPTION.
·

Logic:

· This tag library contains tags that are useful in managing conditional generation of output text, looping over object collections for repetitive generation of output text, and application flow management.
· For tags that do value comparisons (equal, greaterEqual, greaterThan, lessEqual, lessThan, notEqual), the following rules apply:
· The specified value is examined. If it can be converted successfully to a double or a long, it is assumed that the ultimate comparison will be numeric (either floating point or integer). Otherwise, a String comparison will be performed.
· The variable to be compared to is retrieved, based on the selector attribute(s) (cookie, header, name, parameter, property) present on this tag. It will be converted to the appropriate type for the comparison, as determined above.
· If the specified variable or property returns null, it will be coerced to a zero-length string before the comparison occurs. The specific comparison for this tag will be performed, and the nested body content of this tag will be evaluated if the comparison returns a true result. For tags that do substring matching (match, notMatch), the following rules apply:
· The specified variable is retrieved, based on the selector attribute(s) (cookie, header, name, parameter, property) present on this tag. The variable is converted to a String, if necessary. A request time exception will be thrown if the specified variable cannot be retrieved, or has a null value.
· The specified value is checked for existence as a substring of the variable, in the position specified by the location attribute, as follows: at the beginning (if location is set to start), at the end (if location is set to end), or anywhere (if location is not specified). Many of the tags in this tag library will throw a JspException at runtime when they are utilized incorrectly (such as when you specify an invalid combination of tag attributes). JSP allows you to declare an "error page" in the <%@ page %> directive.
· If you wish to process the actual exception that caused the problem, it is passed to the error page as a request attribute under key org.apache.struts.action.EXCEPTION.

Hang on and check this space for more :)

Your rating: None Average: 1 (8 votes)