You are on page 1of 19

Validations in struts

Procedure to perform server side declarative 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
<struts-config>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames"
value="/WEB-INF/validator-rules.xml,/WEBINF/patient.xml"/>
</plug-in>
</struts-config>
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
<message-resources parameter=" MessageResources"/>
Step4: Add default error messages of validator plug-in to the properties file.
Note: Collect these error messages from the comments of validatorrules.xml file.
# Struts Validator Error Messages
errors.header=<font color="red" size=3>
errors.footer=</font>
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:
94

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
<form-bean
name="bean"
type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="username" type="java.lang.String"/>
<form-property name="password" type="java.lang.String"/>
</form-bean>
Step6: Add validation.xml file in WEB-INF folder to apply the required
validator rule on formbean class properties.
In validation.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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="bean">
<field property="username" depends="required,mask">
<arg key="un.error"/>
<msg name="mask" key="un.mask.error"/>
<var>
<var-name>mask</var-name>
<var-value>^[a-zA-Z]*$</var-value>
</var>
</field>
<field property="password" depends="required,mask">
<arg key="pwd.error"/>
<msg name="mask" key="pwd.mask.error"/>
<var>
<var-name>mask</var-name>
<var-value>^[a-zA-Z]*$</var-value>
</var>
</field>
</form>
</formset>
</form-validation>
95

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 username
pwd.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
<action-mappings>
<action
name="bean"
path="/register"
type="RegisterAction"
input="/register.jsp" validate=true scope=session>
<forward name="ok" path="/success.jsp"/>
<forward name="fail" path="/failure.jsp"/>
</action>
</action-mappings>
Step9: Add <html:errors/> tag in input jsp program.
<html:errors/>
Step10: Develop the remaining resources of struts application in regular
manner.
Register.jsp
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<html:html>
<html:form action = "/register">
<table border = 0 align = center>
<tr>
<td><bean:message key="name.username"/>:</td>
<td><html:text property ="username"/></td>
<td><html:errors property="username"/></td>
</tr>
96

<tr>
<td><bean:message key="pwd.password"/>:</td>
<td><html:password property = "password"/></td>
<td><html:errors property="password"/></td>
</tr>
<tr>
<td
colspan="2"
align="center"><html:submit
value="Register"/></td>
</tr>
</table>
</html:form>
</html:html>
RegisterAction.java
import 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
<html>
<body>
<center>
<font size = 5 color = green>Login Successfull</font>
</center>
</body>
</html>
failure.jsp
<html>
<body>
97

<center>
<font size = 5 color = red>Login Failure</font><br>
<a href = "register.jsp">Try Again</a>
</center>
</body>
</html>
Note: Add struts-extras.jar file to the project lib folder.
Note: Test the application with the URL.
http://localhost:9999/webapp/register.jsp
Case1: 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 perform client side declarative 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).
98

<action-mappings>
<action
name="bean"
path="/register"
type="RegisterAction"
input="/register.jsp">
<forward name="ok" path="/success.jsp"/>
<forward name="fail" path="/failure.jsp"/>
</action>
</action-mappings>
Step3: Add <html:javascript formName="bean"/> 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.
<html:form action = "/register" onsubmit="return
validateBean(this);">
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 <html:form> 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/HelpTagsErrorsAndMessage
s.html
http://www.enable-javascript.com/
Procedure to perform client side programmatic 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
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<html>
<head>
<script language="javascript">
function myValidate(frm)
{
//read form data
var unval=frm.username.value;
var pwdval=frm.password.value;
//write programatic client-side form validation logic
99

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()
</script>
</head>
<html:form
action
=
"/register"
onsubmit="return
myValidate(this);">
<table border = 0 align = center>
<tr>
<td><bean:message
key="name.username"/>:</td>
<td><html:text property ="username"/></td>
<td><html:errors property="username"/></td>
100

</tr>
<tr>
<td><bean:message key="pwd.password"/>:</td>
<td><html:password property = "password"/></td>
<td><html:errors property="password"/></td>
</tr>
<tr>
<td colspan="2" align="center"><html:submit
value="Register"/></td>
</tr>
</table>
</html:form>
<html>
Step2: Develop the remaining resources.
Procedure to perform server side programmatic 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=<font color="red" size=3>
errors.footer=</font>
#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 defined
Step2: Configure properties file in Struts-configuration file
In Struts-configuration.xml
<message-resources parameter="MessageResources"/>
Step3: Configure the form bean properties in struts configuration file.
<form-bean name="bean" type="RegisterForm">
<form-property name="username" type="java.lang.String"/>
<form-property name="password" type="java.lang.String"/>
</form-bean>
101

Step4: Override validate () method in form bean class as shown


below.
In RegisterForm.java
import 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
{
102

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
<action
name="bean"
path="/register"
type="RegisterAction"
input="/register.jsp"
scope="request" validate="true">
<forward name="ok" path="/success.jsp"/>
<forward name="fail" path="/failure.jsp"/> </action>
Step5: Add <html:errors/> tag in the input jsp program to decide the
position of displaying from validation error messages.
In register.jsp:
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<html:html>
<html:form action = "/register">
<table border = 0 align = center>
<tr>
<td><bean:message key="name.username"/>:</td>
<td><html:text property ="username"/></td>
<td><html:errors property="unerr"/></td>
</tr>
<tr>
<td><bean:message key="pwd.password"/>:</td>
<td><html:password property = "password"/></td>
<td><html:errors property="pwderr"/></td>
</tr>
<tr>
<td colspan="2" align="center"><html:submit
value="Register"/></td>
</tr>
</table>
</html:form>
</html:html>
103

Step5: Develop the remaining resources of Struts application like our first
application.
Resume Application
Struts validator framework example
Example for server side validations
1. Prototype:

2. PatientRegister.jsp
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<html:form action="/insert">
<center><h1><u>
Registration Screen
</u></h1>
<h2>
<table border = 0 align = center>
<tr>
<td><bean:message key="registration.id" /></td>
<td><html:text property="id" /></td>
<td><html:errors property="id"/></td>
</tr>
<tr>
<td><bean:message key="registration.name" /></td>
<td><html:text property="name" /></td>
<td><html:errors property="name"/></td>
</tr>
<tr>
<td><bean:message key="registration.address" /></td>
<td><html:text property="address" /></td>
<td><html:errors property="address"/></td>
</tr>
104

<tr>
<td><bean:message key="registration.doj" /></td>
<td><html:text property="doj" /></td>
<td><html:errors property="doj"/></td>
</tr>
<tr>
<td><bean:message key="registration.age" /></td>
<td><html:text property="age" /></td>
<td><html:errors property="age"/></td>
</tr>
<tr>
<td><bean:message key="registration.email" /></td>
<td><html:text property="email" /></td>
<td><html:errors property="email"/></td>
</tr>
<tr>
<td><bean:message

key="registration.telephone"

/></td>
<td><html:text property="telephone" /></td>
<td><html:errors property="telephone"/></td>
</tr>
<tr>
<td
colspan="2"
align="center"><html:submit
value="Register"/></td>
</tr>
</table>
</html:form>
3. Patient-config.xml(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/strutsconfig_1_1.dtd">
<struts-config>
<data-sources/>
<form-beans>
<form-bean name="bean"
type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="id" type="java.lang.String" />
<form-property name="name" type="java.lang.String" />
<form-property name="address" type="java.lang.String" />
<form-property name="email" type="java.lang.String" />
<form-property name="doj" type="java.lang.String" />
<form-property name="age" type="java.lang.String" />
<form-property name="telephone" type="java.lang.String"/>
</form-bean>
105

</form-beans>
<global-exceptions/>
<global-forwards/>
<action-mappings>
<action name="bean"
path="/insert"
type="PatientRegisterAction"
input="/patientregister.jsp"
validate="true">
<forward name="ok" path="/Success.html"/>
<forward name="fail" path="/Failure.html"/>
</action>
</action-mappings>
<controller/>
<message-resources null="yes" parameter="Patient"/>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames"
value="/WEB-INF/validator-rules.xml,/WEBINF/patient.xml"/>
</plug-in>
</struts-config>
4. Patient.xml(validation.xml)
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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="bean">
<field property="id" depends="required,integer">
<arg0 key="my.error.id"/>
</field>
<field property="name" depends="required,mask">
<msg name="mask" key="my.error.mask.name"/>
<arg0 key="my.error.name"/>
<var>
<var-name>mask</var-name>
<var-value>^[a-zA-Z]*$</var-value>
</var>
</field>
<field property="address"
depends="required,minlength">
<arg0 key="my.error.address"/>
<arg1 name="minlength" key="${var:minlength}"
resource="false"/>
106

<var>
<var-name>minlength</var-name>
<var-value>10</var-value>
</var>
</field>
<field property="age"
depends="required,integer,intRange">
<arg0 key="my.error.age"/>
<arg1 name="intRange" key="${var:min}"
resource="false"/>
<arg2 name="intRange" key="${var:max}"
resource="false"/>
<var>
<var-name>min</var-name>
<var-value>20</var-value>
</var>
<var>
<var-name>max</var-name>
<var-value>100</var-value>
</var>
</field>
<field property="doj" depends="required,date">
<arg0 key="my.error.doj"/>
<var>
<var-name>datePattern</var-name>
<var-value>yyyy-MM-dd</var-value>
</var>
</field>
<field property="email" depends="required,email">
<arg0 key="my.error.email"/>
</field>
<field property="telephone" depends="required,mask">
<msg name="mask"
key="my.error.mask.telephone"/>
<arg0 key="my.error.telephone"/>
<var>
<var-name>mask</var-name>
<var-value>^\d{5,10}$</var-value>
</var>
</field>
</form>
</formset>
</form-validation>
5. Patient.properties
# Struts Validator Error Messages
107

errors.header=<font color="red" size=3>


errors.footer=</font>
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
108

<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>application</param-name>
<param-value>Patient</param-value>
</init-param>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/patient-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>Register.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>/tags/struts-html</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
</web-app>

7. PatientRegisterAction.java
import 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)
{
109

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)
{}
110

try
{
if(con != null)
con.close();
}
catch(SQLException se)
{}
}
return mapping.findForward(status);
} // execute()
} // class

8. Success.html
<HTML>
<BODY>
<CENTER><BR><BR>
<H1>Registration Successful !!!</H1>
</BODY>
</HTML>
9. Failure.html
<HTML>
<BODY>
<CENTER><BR><BR>
<H1>Registration Failure !!!</H1>
</BODY>
</HTML>

10.
Test the application with the following URL
http://localhost:9999/webapp/patientregister.jsp

Click on register button without enter the data.


111

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

You might also like