Validator Framework example

Introduction

Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used to validate the form data on the client browser. Server side validation of the form can be accomplished by sub classing your From Bean with DynaValidatorForm class. 

The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

The Validator Framework in Struts consist of two XML configuration files. The first one is the validator-rules.xml file which contains the default Struts pluggable validator definitions. You can add new validation rules by adding an entry in this file. The second one is the validation.xml file which contain details regarding the validation routines that are applied to the different Form Beans. These two configuration file should be place somewhere inside the /WEB-INF folder of the application.

Clent Side Address Validation

To accomplish this we have to follow the following steps:

  1. Enabling the Validator plug-in: This makes the Validator available to the system.
  2. Create Message Resources for the displaying the error message to the user.
  3. Developing the Validation rules We have to define the validation rules in the validation.xml for the address form. Struts Validator Framework uses this rule for generating the JavaScript for validation.
  4. Applying the rules: We are required to add the appropriate tag to the JSP for generation of JavaScript.
  5. Build and test: We are required to build the application once the above steps are done before testing. 

Step1:-Make a  web project name viplove and their make a package com.viplove

Step2:-Now a add struts capabilities and after that make a UserForm.Java

UserForm.Java

/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package com.viplove.struts.form;

import org.apache.struts.validator.ValidatorForm;

/** 
 * MyEclipse Struts
 * Creation date: 04-18-2011
 * 
 * XDoclet definition:
 * @struts.form name="userForm"
 */
public class UserForm extends ValidatorForm {
	String username;
	String pwd;
	String pwd2;
	String email;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public String getPwd2() {
		return pwd2;
	}
	public void setPwd2(String pwd2) {
		this.pwd2 = pwd2;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	
}

UserAction.java

Now make a action class name as User Action .java

UserAction.java

/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package com.viplove.struts.action;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.yourcompany.struts.form.UserForm;

	public class UserAction extends Action{
	  

		public ActionForward execute(ActionMapping mapping, ActionForm form,
				HttpServletRequest request, HttpServletResponse response)
				throws Exception {
			UserForm u =(UserForm)form;
			String username = request.getParameter("username");
			String password = request.getParameter("pwd");
			String email = request.getParameter("email");
			String driver = "com.mysql.jdbc.Driver";
			
			String url = "jdbc:mysql://localhost:3306/viplove";
			System.out.println("2");
			try
			{
			Class.forName(driver);
			Connection connection = DriverManager.getConnection(url,"root","root");
			
			String ssql="insert into viploveg(username,password,email) values(?,?,?)";
			PreparedStatement pistmt=connection.prepareStatement(ssql);
			pistmt.setString(1,username);
		    System.out.println("1233");
			pistmt.setString(2,password);
			
			pistmt.setString(3,email);
			int check=0;
			check=pistmt.executeUpdate();
			System.out.println("check......"+check);
			connection.close();
			return mapping.findForward("ThanksYou.jsp"); 
			} catch(Exception ex)
			{
				System.out.println("error");
				ex.printStackTrace();
			
		

			}
			return mapping.findForward("RegisterUser.jsp");
		}
	}

Now we would make the client representation thatis HTML and Jsp Page

RegisterUser.jsp

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


<b>User Registeration Form</b>
<br/><br/>

<font color="red">
<html:errors/>
</font>

<html:form action="/Register">

<br/>
<bean:message key="label.user.username" /> : 
<html:text property="username" size="20"/>
<br/>
<bean:message key="label.user.pwd" /> : 
<html:text property="pwd" size="20"/>
<br/>
<bean:message key="label.user.pwd2" /> : 
<html:text property="pwd2" size="20"/>
<br/>
<bean:message key="label.user.email" /> : 
<html:text property="email" size="20"/>
<br/><br/>
<html:submit>
<bean:message key="label.user.button.submit" />
</html:submit>

</html:form>

</body>
</html>

ThanksYou.jsp

<html>
<head>
</head>
<body>

<h2>Struts - Validator Example</h2>

Thanks you for the registration

</body>
 </html>

Validation

After these Now we would apply validations on the form we need two xml file

1.validation-rules.xml:-These the predefined sets of rule

2.validation.xml :-Inthese we define the validation which is to be performed on our form

Validation.xml

<!DOCTYPE form-validation PUBLIC
        "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.3.0//EN"
        "http://jakarta.apache.org/commons/dtds/validator_1_3_0.dtd">

<form-validation>
   <formset>
      <form name="userForm">
         <field property="username" depends="required,maxlength,minlength,mask">
         
         	<msg name="required" key="err.user.username.required" />
			<msg name="maxlength" key="err.user.username.length" />
			<msg name="minlength" key="err.user.username.length" />
			<msg name="mask" key="err.user.username.invalid" />

			<arg name="maxlength" key="${var:minlength}" position="0" resource="false"/>
            <arg name="maxlength" key="${var:maxlength}" position="1" resource="false"/>

			<arg name="minlength" key="${var:minlength}" position="0" resource="false"/>
            <arg name="minlength" key="${var:maxlength}" position="1" resource="false"/>
            
            <var>
            	<var-name>minlength</var-name>
				<var-value>3</var-value>
			</var>		
			<var>
				<var-name>maxlength</var-name>
				<var-value>15</var-value>
			</var>
            
            <var>
				<var-name>mask</var-name>
				<var-value>^[a-zA-Z0-9-_]*$</var-value>
			</var>
			
         </field>
         
         <field property="pwd" depends="required,maxlength,minlength,mask">
         
         	<msg name="required" key="err.user.pwd.required" />
			<msg name="maxlength" key="err.user.pwd.length" />
			<msg name="minlength" key="err.user.pwd.length" />
			<msg name="mask" key="err.user.pwd.invalid" />

			<arg name="maxlength" key="${var:minlength}" position="0" resource="false"/>
            <arg name="maxlength" key="${var:maxlength}" position="1" resource="false"/>

			<arg name="minlength" key="${var:minlength}" position="0" resource="false"/>
            <arg name="minlength" key="${var:maxlength}" position="1" resource="false"/>
            
            <var>
            	<var-name>minlength</var-name>
				<var-value>7</var-value>
			</var>		
			<var>
				<var-name>maxlength</var-name>
				<var-value>15</var-value>
			</var>
            
            <var>
				<var-name>mask</var-name>
				<var-value>^[a-zA-Z0-9]*$</var-value>
			</var>
			
         </field>
         
         <field property="pwd2" depends="validwhen">
         
         	<msg name="validwhen" key="err.user.pwd2.notmatch" />
         
			<var>
				<var-name>test</var-name>
				<var-value>
					(pwd == *this*)
				</var-value>
				</var>
		 </field>

		 <field property="email" depends="required,email">
		 
		 	<msg name="required" key="err.user.email.required" />
		 	<msg name="email" key="err.user.email.invalid" />

		 </field>
		 
		
		
     </form>
  </formset>
</form-validation>

Now some validation are to be written in ApplicationResources file

ApplicationResources.Properties

#user module label message
label.user.name = Name
label.user.username = UserName
label.user.pwd = Password
label.user.pwd2 = Confirm Password
label.user.email = Email

label.user.button.submit = Submit

#Error message
err.user.username.required = Username is required.<br/>
err.user.username.length = Username length should be between {0} and {1}.<br/>
err.user.username.invalid = Username is invalid , it should be a-z, A-Z, 0-9, dash "-" or underscore "_".<br/>

err.user.pwd.required = Password is required.<br/>
err.user.pwd.length = Password length should be between {0} and {1}.<br/>
err.user.pwd.invalid = Password is invalid , it should be a-z, A-Z, 0-9.<br/>

err.user.pwd2.notmatch = Confirm password is not match.<br/>

err.user.email.required = Email is required.<br/>
err.user.email.invalid =  Email address is invalid.<br/>

Configure struts.xml

Now we have done validation the thing left is controller design

Controller is strutsconfig.xml to mapp  model and view

Struts-Config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>
  <data-sources />
  <form-beans >
    <form-bean name="userForm" type="com.yourcompany.struts.form.UserForm" />

  </form-beans>

  <global-exceptions />
  <global-forwards />
  <action-mappings >
    <action
      path="/Register"
      name="userForm"
      type="com.yourcompany.struts.action.UserAction" 
      input="/RegisterUser.jsp"
      validate="true"
      scope="request">
      <forward name="success" path="/ThanksYou.jsp "/>
</action>

		<action
			path="/RegisterUserPage"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/RegisterUser.jsp"/>
		
	</action-mappings>

  <message-resources parameter="com.yourcompany.struts.ApplicationResources" />
  <plug-in className="org.apache.struts.validator.ValidatorPlugIn" >
		<set-property property="pathnames"
		value="/WEB-INF/validator-rules.xml, /WEB-INF/validator-user.xml"/>
		
	</plug-in>
  
</struts-config>

Run

Now Run Your code and enjoy and dont forget to  comment how it worked........

Comments

No comments yet.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working