SlideShare a Scribd company logo
1 of 26
Validation in Jakarta Struts 1.3
Ilio Catallo – info@iliocatallo.it
Outline
¤ HTML forms vs. web apps
¤ Struts validation
¤ Validation via the validate() method
¤ Validation via the Validator framework
¤ References
2
HTML forms vs. web apps
HTML form vs. web apps
¤ While HTML forms give users a place to enter data, they
do not give web apps a place to put such data
¤ The browser sends the data up to the server as a list of
name-value pairs
¤ Everything is going to be transferred to the web app as a
string
¤ HTTP/HTML does not provide a component that can
buffer, validate and convert inputs coming from a form
¤ That is the way HTTP and HTML work, web applications
cannot control this
4
HTML forms vs. Struts
¤ The Struts solution to HTTP data-entry problem is made of:
¤ the ActionForm class that provides a
buffer/validate/convert mechanism to ensure that users
enter what they are supposed to enter
¤ A set of JSP tags to bind the HTML form to the related
ActionForm object
¤ JSP tags allow developers to pre-populate a form with
any data the user may have to revise if validation fails
5
ActionForm’s responsibilities
¤ ActionForm is a versatile object, and can play different
roles even within the span of the same request:
¤ Field collector: developers can work with a trusty JavaBean
and leave all the HTML/HTTP issues to the framework
¤ Data buffer: ActionForm is not the destination of the input,
but a buffer that preserves the input until it can be validated
and committed to the business layer
¤ Data validator: many fields must be the correct type before
they can be processed by the business logic. The
validate() method can be used to determine if the input is
of the right type
6
Validation Part I
Manual validation
ActionForm’s life cycle
¤ The base ActionForm class includes two standard methods:
¤ reset(), which resets the form to its default state, as needed
¤ validate(), which checks if the data look correct and if all
required fields have been submitted
¤ Once the Controller receives the HTTP request:
¤ It creates the related ActionForm object in the proper context
(if not already present)
¤ It calls the reset() method on the ActionForm
¤ Starting from the HTTP request, it populates the ActionForm’s
properties
¤ It calls the validate() method on the ActionForm
8
Manual validation:
validate() signature
validate() signature
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request)
¤ ActionErrors is a specialization of ActionMessages
¤ It encapsulates the error messages being reported by the
validate() method
¤ The returned ActionErrors object is stored in the
request context under the Globals.ERROR_KEY key
¤ Validation fails when the returned ActionErrors object
is not empty
9
Manual validation:
struts-config.xml
struts-config.xml (snippet)
<action path="/register"
type="it.polimi.awt.struts.RegisterAction"
name="registerForm"
validate="true"
input="/register.jsp">
...
</action>
¤ When the mapping is set to validate=“true”, the validation
method is called after the form is populated from the HTTP
request
¤ The input property specifies where to send control if the
validate() method fails
10
Displaying errors:
Application resources (1/2)
¤ We would like to inform the user that the web app
encountered some problems while trying to validate the
data he or she submitted
¤ To this end, each possible error is associated with a
description (i.e., a message) and an identification key
¤ The (key, message) pairs are stored in a standard Java
Properties file, i.e., a text file stored in the web app’s
CLASSPATH
¤ When the View needs to display an error, it can refer to its
description by its key
¤ In the Struts glossary, we will refer to this Properties file as
the applicationresources or (message) resource bundle
11
Displaying errors:
Application resources (2/2)
application.properties (snippet)
registerform.email.msg=Invalid e-mail address
struts-config.xml (snippet)
<message-resources parameter="resources.application"/>
¤ The <message-resources> element is used to deploy whatever
bundle the application may need to use
¤ The location of application.properties is intended as a
Java package
¤ In this case, CLASSPATH/resources/application.properties
12
Displaying errors:
<html:errors>
Displaying possible errors encountered during the validation phase
<html:errors/>
¤ The <html:errors> tag will render the error messages
when they exist, or do nothing when they do not exist
¤ The HTML markup surrounding the errors can be kept out
of the message by means of two specific keys in the
resource bundle:
¤ errors.prefix
¤ errors.suffix
13
Validation Part II
Jakarta Validator Framework
Validation system requirements (1/2)
¤ Problem: inputs need to be validated by the Controller,
but validation rules must be kept synchronized with
business requirements
¤ Problem: in a distributed application, the business layer
may reside on a remote machine
¤ Creating round trips to resolve simple data-entry errors may
be costly
15
Validation system requirements (2/2)
¤ Solving such problems means introducing two important
requirements for a validation system:
¤ Loose coupling: the validation rules should be stored
separately from markup or Java code so that they can be
reviewed and modified without changing any other source
code
¤ Client-side validation: generating JavaScript and server-side
validations from the same set of rules
¤ Even if JavaScript is disabled, the input is still validated
server-side to ensure nothing is amiss
16
Jakarta Validator framework(1/3)
¤ The Jakarta Commons Validator framework meets the
afore-mentioned requirements:
¤ It is configured from an XML file that generates validation
rules for the form fields
¤ It provides a set of custom tags and JavaScript functions to
be used for client-side validation
¤ the Commons Validator was created as an extension to
the Struts framework
¤ Since it could also be used outside the framework, the
developers contributed it to the Commons project
17
Jakarta Validator framework(2/3)
¤ The Validator framework uses two XML configuration files:
¤ validator-rules.xml: it defines a set of ready-to-use
validation routines (i.e., validators)
¤ validation.xml: it maps each form field with a
corresponding validator
¤ The Validator framework includes validators for native
types and other common needs, like e-mail and credit
card validations
¤ If a custom validator is needed, it can be defined along
with the basic validators
18
Jakarta Validator framework(3/3)
¤ Starting from Struts 1.3, validator-rules.xml has been
included in the struts-core JAR file
¤ If basic validators are enough, nothing has to be done to
use them in validation.xml
¤ If custom validators are still needed, they can be defined
in a separate /WEB-INF/validator-rules.xml file
19
Basic validators
Validators Purpose
required Succeeds if the field contains any
character other than whitespace
mask Succeeds if the field value matches
the specified regular expression
range Succeeds if the field value is within a
specific range
date Succeeds if the field contains a date
email Succeeds if the field value is
recognized as a valid e-mail address
validwhen*
Succeeds when a specified
condition is verified
20
* server-side only
Validation via the
Validator Framework
¤ In order to use the Validator framework we need to
perform three steps:
¤ Plugging the Validator framework in Struts
¤ Configuring the Validator framework
¤ Enabling client-side validation (optional)
21
Step 1: Plugging the Validator
framework in Struts
struts-config.xml (snippet)
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames"
value="/org/apache/struts/validator/validator-
rules.xml,
/WEB-INF/validation.xml"/>
</plug-in>
¤ Special resources are implemented in the Struts
framework as plug-ins
¤ To this end, ValidatorPlugIn (i.e., the Validator
framework) implements the
org.apache.struts.action.PlugIn interface
validator-rules.xml
inside the struts-core
JAR file
22
Step 2: Configuring the Validator
framework (1/2)
validation.xml (snippet)
<formset>
<form name="registerForm">
<field property="email" depends="required,email">
<msg name="email" key="registerform.email.emailmsg"/>
<msg name="required" key="registerform.email.requiredmsg"/>
</field>
...
</form>
</formset>
¤ The Struts resource bundle is automatically shared with the
Validator framework
¤ For each validator, a specific entry in the resource bundle can
be specified by means of the <msg> tag
basic
validators to
be used
23
name of the
ActionForm’s
property
Step 2: Configuring the Validator
framework (2/2)
RegisterForm.java (snippet)
import org.apache.struts.validator.*;
public class RegisterForm extends ValidatorForm {
¤ To enable validation via the Validation framework:
¤ The form bean must extend ValidatorForm, instead of
ActionForm
¤ The validate() method must be removed
24
Step 3:
Enabling client-side validation
register.jsp (snippet)
<html:javascript formName="registerForm"/>
<html:form action="/register"
onsubmit="return validateRegisterForm(this);">
...
</html:form>
¤ The <html:javascript> tag generates all the
JavaScript code in charge of validating the form
¤ It can be placed anywhere in the page
¤ The entry-point function is validateFormName()
¤ The onsubmit attribute calls the validation script before
submitting the form
25
References
¤ Struts 1 In Action, T. N. Husted, C. Dumoulin, G. Franciscus,
D. Winterfeldt, Manning Publications Co
¤ Struts Validator Guide,
http://struts.apache.org/release/1.3.x/faqs/validator.html
26

More Related Content

What's hot

Spring MVC Annotations
Spring MVC AnnotationsSpring MVC Annotations
Spring MVC AnnotationsJordan Silva
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session ManagementFahad Golra
 
Railsplitter: Simplify Your CRUD
Railsplitter: Simplify Your CRUDRailsplitter: Simplify Your CRUD
Railsplitter: Simplify Your CRUDFlurry, Inc.
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Tuna Tore
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desaijinaldesailive
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questionsAkhil Mittal
 
Asp dot-net core problems and fixes
Asp dot-net core problems and fixes Asp dot-net core problems and fixes
Asp dot-net core problems and fixes sonia merchant
 
Silverlight2 Security
Silverlight2 SecuritySilverlight2 Security
Silverlight2 SecurityReagan Hwang
 
Automation Framework 042009 V2
Automation Framework   042009  V2Automation Framework   042009  V2
Automation Framework 042009 V2guestb66d91
 
Identifing Listeners and Filters
Identifing Listeners and FiltersIdentifing Listeners and Filters
Identifing Listeners and FiltersPeople Strategists
 

What's hot (20)

Struts course material
Struts course materialStruts course material
Struts course material
 
The most basic inline tag
The most basic inline tagThe most basic inline tag
The most basic inline tag
 
Spring MVC Annotations
Spring MVC AnnotationsSpring MVC Annotations
Spring MVC Annotations
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
Exploring Maven SVN GIT
Exploring Maven SVN GITExploring Maven SVN GIT
Exploring Maven SVN GIT
 
Spring MVC 3.0 Framework
Spring MVC 3.0 FrameworkSpring MVC 3.0 Framework
Spring MVC 3.0 Framework
 
Railsplitter: Simplify Your CRUD
Railsplitter: Simplify Your CRUDRailsplitter: Simplify Your CRUD
Railsplitter: Simplify Your CRUD
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questions
 
TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1
 
70562 (1)
70562 (1)70562 (1)
70562 (1)
 
Asp dot-net core problems and fixes
Asp dot-net core problems and fixes Asp dot-net core problems and fixes
Asp dot-net core problems and fixes
 
Servlets lecture1
Servlets lecture1Servlets lecture1
Servlets lecture1
 
Silverlight2 Security
Silverlight2 SecuritySilverlight2 Security
Silverlight2 Security
 
Automation Framework 042009 V2
Automation Framework   042009  V2Automation Framework   042009  V2
Automation Framework 042009 V2
 
Struts notes
Struts notesStruts notes
Struts notes
 
Identifing Listeners and Filters
Identifing Listeners and FiltersIdentifing Listeners and Filters
Identifing Listeners and Filters
 
Marata
MarataMarata
Marata
 
Working with Servlets
Working with ServletsWorking with Servlets
Working with Servlets
 

Similar to Validation in Jakarta Struts 1.3

Validate your entities with symfony validator and entity validation api
Validate your entities with symfony validator and entity validation apiValidate your entities with symfony validator and entity validation api
Validate your entities with symfony validator and entity validation apiRaffaele Chiocca
 
Introduction to Struts 1.3
Introduction to Struts 1.3Introduction to Struts 1.3
Introduction to Struts 1.3Ilio Catallo
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentChui-Wen Chiu
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's NewTed Pennings
 
New Features Of ASP.Net 4 0
New Features Of ASP.Net 4 0New Features Of ASP.Net 4 0
New Features Of ASP.Net 4 0Dima Maleev
 
Overview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company indiaOverview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company indiaJignesh Aakoliya
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing Techglyphs
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedBG Java EE Course
 
Auto fac mvc以及進階應用(一)
Auto fac mvc以及進階應用(一)Auto fac mvc以及進階應用(一)
Auto fac mvc以及進階應用(一)LearningTech
 
Struts Interview Questions
Struts Interview QuestionsStruts Interview Questions
Struts Interview Questionsjbashask
 
SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4Ben Abdallah Helmi
 
Unit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptxUnit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptxAbhijayKulshrestha1
 
Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS�Using Java to implement SOAP Web Services: JAX-WS�
Using Java to implement SOAP Web Services: JAX-WSKatrien Verbert
 
Webformer: a Rapid Application Development Toolkit for Writing Ajax Web Form ...
Webformer: a Rapid Application Development Toolkit for Writing Ajax Web Form ...Webformer: a Rapid Application Development Toolkit for Writing Ajax Web Form ...
Webformer: a Rapid Application Development Toolkit for Writing Ajax Web Form ...Thomas Lee
 

Similar to Validation in Jakarta Struts 1.3 (20)

Validate your entities with symfony validator and entity validation api
Validate your entities with symfony validator and entity validation apiValidate your entities with symfony validator and entity validation api
Validate your entities with symfony validator and entity validation api
 
AJAX
AJAXAJAX
AJAX
 
AJAX
AJAXAJAX
AJAX
 
Introduction to Struts 1.3
Introduction to Struts 1.3Introduction to Struts 1.3
Introduction to Struts 1.3
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component Development
 
Spring REST Request Validation
Spring REST Request ValidationSpring REST Request Validation
Spring REST Request Validation
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
 
New Features Of ASP.Net 4 0
New Features Of ASP.Net 4 0New Features Of ASP.Net 4 0
New Features Of ASP.Net 4 0
 
Overview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company indiaOverview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company india
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
Oip presentation
Oip presentationOip presentation
Oip presentation
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
 
Struts N E W
Struts N E WStruts N E W
Struts N E W
 
Auto fac mvc以及進階應用(一)
Auto fac mvc以及進階應用(一)Auto fac mvc以及進階應用(一)
Auto fac mvc以及進階應用(一)
 
Struts Interview Questions
Struts Interview QuestionsStruts Interview Questions
Struts Interview Questions
 
SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4
 
Unit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptxUnit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptx
 
Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS�Using Java to implement SOAP Web Services: JAX-WS�
Using Java to implement SOAP Web Services: JAX-WS
 
Webformer: a Rapid Application Development Toolkit for Writing Ajax Web Form ...
Webformer: a Rapid Application Development Toolkit for Writing Ajax Web Form ...Webformer: a Rapid Application Development Toolkit for Writing Ajax Web Form ...
Webformer: a Rapid Application Development Toolkit for Writing Ajax Web Form ...
 
JavaScript
JavaScriptJavaScript
JavaScript
 

More from Ilio Catallo

C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template LibraryIlio Catallo
 
Regular types in C++
Regular types in C++Regular types in C++
Regular types in C++Ilio Catallo
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++Ilio Catallo
 
Memory management in C++
Memory management in C++Memory management in C++
Memory management in C++Ilio Catallo
 
Operator overloading in C++
Operator overloading in C++Operator overloading in C++
Operator overloading in C++Ilio Catallo
 
Multidimensional arrays in C++
Multidimensional arrays in C++Multidimensional arrays in C++
Multidimensional arrays in C++Ilio Catallo
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++Ilio Catallo
 
Spring MVC - Wiring the different layers
Spring MVC -  Wiring the different layersSpring MVC -  Wiring the different layers
Spring MVC - Wiring the different layersIlio Catallo
 
Java and Java platforms
Java and Java platformsJava and Java platforms
Java and Java platformsIlio Catallo
 
Spring MVC - Web Forms
Spring MVC  - Web FormsSpring MVC  - Web Forms
Spring MVC - Web FormsIlio Catallo
 
Spring MVC - The Basics
Spring MVC -  The BasicsSpring MVC -  The Basics
Spring MVC - The BasicsIlio Catallo
 
Web application architecture
Web application architectureWeb application architecture
Web application architectureIlio Catallo
 
Introduction To Spring
Introduction To SpringIntroduction To Spring
Introduction To SpringIlio Catallo
 
Gestione della memoria in C++
Gestione della memoria in C++Gestione della memoria in C++
Gestione della memoria in C++Ilio Catallo
 
Puntatori e Riferimenti
Puntatori e RiferimentiPuntatori e Riferimenti
Puntatori e RiferimentiIlio Catallo
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence APIIlio Catallo
 
JSP Standard Tag Library
JSP Standard Tag LibraryJSP Standard Tag Library
JSP Standard Tag LibraryIlio Catallo
 
Internationalization in Jakarta Struts 1.3
Internationalization in Jakarta Struts 1.3Internationalization in Jakarta Struts 1.3
Internationalization in Jakarta Struts 1.3Ilio Catallo
 

More from Ilio Catallo (20)

C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template Library
 
Regular types in C++
Regular types in C++Regular types in C++
Regular types in C++
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++
 
Memory management in C++
Memory management in C++Memory management in C++
Memory management in C++
 
Operator overloading in C++
Operator overloading in C++Operator overloading in C++
Operator overloading in C++
 
Multidimensional arrays in C++
Multidimensional arrays in C++Multidimensional arrays in C++
Multidimensional arrays in C++
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++
 
Spring MVC - Wiring the different layers
Spring MVC -  Wiring the different layersSpring MVC -  Wiring the different layers
Spring MVC - Wiring the different layers
 
Java and Java platforms
Java and Java platformsJava and Java platforms
Java and Java platforms
 
Spring MVC - Web Forms
Spring MVC  - Web FormsSpring MVC  - Web Forms
Spring MVC - Web Forms
 
Spring MVC - The Basics
Spring MVC -  The BasicsSpring MVC -  The Basics
Spring MVC - The Basics
 
Web application architecture
Web application architectureWeb application architecture
Web application architecture
 
Introduction To Spring
Introduction To SpringIntroduction To Spring
Introduction To Spring
 
Gestione della memoria in C++
Gestione della memoria in C++Gestione della memoria in C++
Gestione della memoria in C++
 
Array in C++
Array in C++Array in C++
Array in C++
 
Puntatori e Riferimenti
Puntatori e RiferimentiPuntatori e Riferimenti
Puntatori e Riferimenti
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence API
 
JSP Standard Tag Library
JSP Standard Tag LibraryJSP Standard Tag Library
JSP Standard Tag Library
 
Internationalization in Jakarta Struts 1.3
Internationalization in Jakarta Struts 1.3Internationalization in Jakarta Struts 1.3
Internationalization in Jakarta Struts 1.3
 

Validation in Jakarta Struts 1.3

  • 1. Validation in Jakarta Struts 1.3 Ilio Catallo – info@iliocatallo.it
  • 2. Outline ¤ HTML forms vs. web apps ¤ Struts validation ¤ Validation via the validate() method ¤ Validation via the Validator framework ¤ References 2
  • 3. HTML forms vs. web apps
  • 4. HTML form vs. web apps ¤ While HTML forms give users a place to enter data, they do not give web apps a place to put such data ¤ The browser sends the data up to the server as a list of name-value pairs ¤ Everything is going to be transferred to the web app as a string ¤ HTTP/HTML does not provide a component that can buffer, validate and convert inputs coming from a form ¤ That is the way HTTP and HTML work, web applications cannot control this 4
  • 5. HTML forms vs. Struts ¤ The Struts solution to HTTP data-entry problem is made of: ¤ the ActionForm class that provides a buffer/validate/convert mechanism to ensure that users enter what they are supposed to enter ¤ A set of JSP tags to bind the HTML form to the related ActionForm object ¤ JSP tags allow developers to pre-populate a form with any data the user may have to revise if validation fails 5
  • 6. ActionForm’s responsibilities ¤ ActionForm is a versatile object, and can play different roles even within the span of the same request: ¤ Field collector: developers can work with a trusty JavaBean and leave all the HTML/HTTP issues to the framework ¤ Data buffer: ActionForm is not the destination of the input, but a buffer that preserves the input until it can be validated and committed to the business layer ¤ Data validator: many fields must be the correct type before they can be processed by the business logic. The validate() method can be used to determine if the input is of the right type 6
  • 8. ActionForm’s life cycle ¤ The base ActionForm class includes two standard methods: ¤ reset(), which resets the form to its default state, as needed ¤ validate(), which checks if the data look correct and if all required fields have been submitted ¤ Once the Controller receives the HTTP request: ¤ It creates the related ActionForm object in the proper context (if not already present) ¤ It calls the reset() method on the ActionForm ¤ Starting from the HTTP request, it populates the ActionForm’s properties ¤ It calls the validate() method on the ActionForm 8
  • 9. Manual validation: validate() signature validate() signature public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) ¤ ActionErrors is a specialization of ActionMessages ¤ It encapsulates the error messages being reported by the validate() method ¤ The returned ActionErrors object is stored in the request context under the Globals.ERROR_KEY key ¤ Validation fails when the returned ActionErrors object is not empty 9
  • 10. Manual validation: struts-config.xml struts-config.xml (snippet) <action path="/register" type="it.polimi.awt.struts.RegisterAction" name="registerForm" validate="true" input="/register.jsp"> ... </action> ¤ When the mapping is set to validate=“true”, the validation method is called after the form is populated from the HTTP request ¤ The input property specifies where to send control if the validate() method fails 10
  • 11. Displaying errors: Application resources (1/2) ¤ We would like to inform the user that the web app encountered some problems while trying to validate the data he or she submitted ¤ To this end, each possible error is associated with a description (i.e., a message) and an identification key ¤ The (key, message) pairs are stored in a standard Java Properties file, i.e., a text file stored in the web app’s CLASSPATH ¤ When the View needs to display an error, it can refer to its description by its key ¤ In the Struts glossary, we will refer to this Properties file as the applicationresources or (message) resource bundle 11
  • 12. Displaying errors: Application resources (2/2) application.properties (snippet) registerform.email.msg=Invalid e-mail address struts-config.xml (snippet) <message-resources parameter="resources.application"/> ¤ The <message-resources> element is used to deploy whatever bundle the application may need to use ¤ The location of application.properties is intended as a Java package ¤ In this case, CLASSPATH/resources/application.properties 12
  • 13. Displaying errors: <html:errors> Displaying possible errors encountered during the validation phase <html:errors/> ¤ The <html:errors> tag will render the error messages when they exist, or do nothing when they do not exist ¤ The HTML markup surrounding the errors can be kept out of the message by means of two specific keys in the resource bundle: ¤ errors.prefix ¤ errors.suffix 13
  • 14. Validation Part II Jakarta Validator Framework
  • 15. Validation system requirements (1/2) ¤ Problem: inputs need to be validated by the Controller, but validation rules must be kept synchronized with business requirements ¤ Problem: in a distributed application, the business layer may reside on a remote machine ¤ Creating round trips to resolve simple data-entry errors may be costly 15
  • 16. Validation system requirements (2/2) ¤ Solving such problems means introducing two important requirements for a validation system: ¤ Loose coupling: the validation rules should be stored separately from markup or Java code so that they can be reviewed and modified without changing any other source code ¤ Client-side validation: generating JavaScript and server-side validations from the same set of rules ¤ Even if JavaScript is disabled, the input is still validated server-side to ensure nothing is amiss 16
  • 17. Jakarta Validator framework(1/3) ¤ The Jakarta Commons Validator framework meets the afore-mentioned requirements: ¤ It is configured from an XML file that generates validation rules for the form fields ¤ It provides a set of custom tags and JavaScript functions to be used for client-side validation ¤ the Commons Validator was created as an extension to the Struts framework ¤ Since it could also be used outside the framework, the developers contributed it to the Commons project 17
  • 18. Jakarta Validator framework(2/3) ¤ The Validator framework uses two XML configuration files: ¤ validator-rules.xml: it defines a set of ready-to-use validation routines (i.e., validators) ¤ validation.xml: it maps each form field with a corresponding validator ¤ The Validator framework includes validators for native types and other common needs, like e-mail and credit card validations ¤ If a custom validator is needed, it can be defined along with the basic validators 18
  • 19. Jakarta Validator framework(3/3) ¤ Starting from Struts 1.3, validator-rules.xml has been included in the struts-core JAR file ¤ If basic validators are enough, nothing has to be done to use them in validation.xml ¤ If custom validators are still needed, they can be defined in a separate /WEB-INF/validator-rules.xml file 19
  • 20. Basic validators Validators Purpose required Succeeds if the field contains any character other than whitespace mask Succeeds if the field value matches the specified regular expression range Succeeds if the field value is within a specific range date Succeeds if the field contains a date email Succeeds if the field value is recognized as a valid e-mail address validwhen* Succeeds when a specified condition is verified 20 * server-side only
  • 21. Validation via the Validator Framework ¤ In order to use the Validator framework we need to perform three steps: ¤ Plugging the Validator framework in Struts ¤ Configuring the Validator framework ¤ Enabling client-side validation (optional) 21
  • 22. Step 1: Plugging the Validator framework in Struts struts-config.xml (snippet) <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/org/apache/struts/validator/validator- rules.xml, /WEB-INF/validation.xml"/> </plug-in> ¤ Special resources are implemented in the Struts framework as plug-ins ¤ To this end, ValidatorPlugIn (i.e., the Validator framework) implements the org.apache.struts.action.PlugIn interface validator-rules.xml inside the struts-core JAR file 22
  • 23. Step 2: Configuring the Validator framework (1/2) validation.xml (snippet) <formset> <form name="registerForm"> <field property="email" depends="required,email"> <msg name="email" key="registerform.email.emailmsg"/> <msg name="required" key="registerform.email.requiredmsg"/> </field> ... </form> </formset> ¤ The Struts resource bundle is automatically shared with the Validator framework ¤ For each validator, a specific entry in the resource bundle can be specified by means of the <msg> tag basic validators to be used 23 name of the ActionForm’s property
  • 24. Step 2: Configuring the Validator framework (2/2) RegisterForm.java (snippet) import org.apache.struts.validator.*; public class RegisterForm extends ValidatorForm { ¤ To enable validation via the Validation framework: ¤ The form bean must extend ValidatorForm, instead of ActionForm ¤ The validate() method must be removed 24
  • 25. Step 3: Enabling client-side validation register.jsp (snippet) <html:javascript formName="registerForm"/> <html:form action="/register" onsubmit="return validateRegisterForm(this);"> ... </html:form> ¤ The <html:javascript> tag generates all the JavaScript code in charge of validating the form ¤ It can be placed anywhere in the page ¤ The entry-point function is validateFormName() ¤ The onsubmit attribute calls the validation script before submitting the form 25
  • 26. References ¤ Struts 1 In Action, T. N. Husted, C. Dumoulin, G. Franciscus, D. Winterfeldt, Manning Publications Co ¤ Struts Validator Guide, http://struts.apache.org/release/1.3.x/faqs/validator.html 26