advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

Tutorials : Data Validation with the Spring Framework :

 

Calling Your Validators

Now that your validators are complete, how do you call them? The most effective way is to use Spring aspect oriented programming ( AOP). AOP is a large subject, so we’ll only cover what you need to know right now.

In a nutshell, AOP allows you to implement cross-cutting concerns in ways that are not destructive or imposing to your existing code base. The power in AOP's usage is it's ability to select a location within an application, called a pointcut. Once a pointcut has been located, advice can be applied. Advice is what you intend to perform at the pointcut, things like logging, validation, security, etc. AOP is applicable in many situations, but in this case, you want to validate the TaskService's method arguments if they are supported by a validator. Additionally, you don't need to limit your service—you can apply validation to all service methods with at least one argument. Basically, you need a way to intercept method calls while having knowledge of the arguments passed to that method. Thankfully, Spring has an interceptor for the job:MethodInterceptor. When implemented, the MethodInterceptor interface provides just about everything you need to know about a method invocation as well as the opportunity to perform validation before a method's call. If a validation error has occurred, you’ll throw a ValidationException like the one shown below. If a ValidationException occurs, method invocation will not, thus giving you peace-of-mind knowing that invalid data will not reach the task service implementation.

<ValidationException> 
package jbriscoe.article.spring.validation.exception;

import java.util.List;

import org.springframework.validation.Errors;

public class ValidationException extends RuntimeException {

  private List<Errors> errors;

  public ValidationException(final List<Errors> errors) {
    this.errors = errors;
  }
  public List<Errors> getErrors() {
    return errors;
  }
  public void setErrors(final List<Errors> errors) {
    this.errors = errors;
  }
}
The ValidationException class contains a List of Spring validation errors that have occurred, which should provide your calling code all the information it needs to determine what validation failed. ValidationException is a RuntimeException that will not force the service implementation to declare that it throws a ValidationException. However, the TaskService interface must be updated declaring that it throws a ValidationException.
< Final TaskService Interface>
public Boolean createTask(final Task task) throws ValidationException;
Implementing the validation method interceptor is relatively simple. However, an object that is supported by a validator (Task, Employee, etc) can contain any number of nested fields that are themselves supported by a validator. For instance, the Address class is supported by the AddressValidator but, in order to validate it, you’ll need code that recursively inspects a validator supported class and it's fields, and it's fields, and so on, until all fields that can be validated have been. Therefore, no limitations have been made on the depth of objects that can be validated. The only limitation is: a class you would want to be validated must be contained by a class that can be validated. For example, suppose the Employee class contained another object called Floor. If Floor did not have a validator, any fields within Floor that have a validator will not be validated—including the Floor class. The final implementation of MethodInterceptor is shown in Listing 8.

The MethodArgValidationInterceptor contains a List of Validators (TaskValidator, EmployeeValidator, and AddressValidator). You need to update the tasklist-core.xml file, which tells Spring about the new interceptor and where to apply it. As stated earlier, pointcuts describe a location to apply advice. The RegexpMethodPointcutAdvisor is one of a few pointcuts Spring offers. With it, you specify the task service with a regular expression like jbriscoe.article.spring.validation.service.*. This regular expression allows you to select any class within the service package. You’ll use the RegexpMethodPointcutAdvisor in this app as it meets all of the task service's needs. Now that you’ve selected a pointcut, you need to provide the advice by setting the advice property to the MethodArgValidationInterceptor bean. The updated tasklist-core.xml file is shown below:

<Update tasklist-core.xml>

<bean id="serviceValidationAdvisor"
  class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
  <property name="pattern" value="jbriscoe.article.spring.validation.service.*" />
  <property name="advice">
  <bean  class="jbriscoe.article.spring.validation.interceptor.MethodArgValidationIntercepto  r">
    <property name="validators">
	<list>
	  <bean		    class=
	  "jbriscoe.article.spring.validation.validator.TaskValidator" />
	  <bean				    class=
	  "jbriscoe.article.spring.validation.validator.EmployeeValidator" />
	  <bean					    class=
	  "jbriscoe.article.spring.validation.validator.AddressValidator" />
	</list>
    </property>
  </bean>
 </property>
</bean>
<bean id="advisorAutoProxyCreator"
class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />
There’s enough in place now to perform a test—this time with invalid data. When you execute the createTask method on the task service this time, expect the task creation to not occur and receive a ValidationException. Create a new invalid Task object in the tasklist-test.xml file similar to the one shown in Listing 9.

Add the new task object as a protected property, to be injected into the TaskServiceTest. Then add a new test with new assertions ( Listing 10).

Run your test case. You should see output similar to that in Figure 3.


Figure 3. Running Your Last Test Case:
You should see similar output to this when you run your last test case.

 

A Consistent—If Not Perfect—Solution

This is one approach to validating your objects in a Spring Framework application. The task of validating data will never go away—you’ll always need to address it in some way or another and there is no silver bullet. But by using Spring and AOP together, you can at least ensure that your applications handle it consistently.

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 Intel Go Parallel Portal
 Internet.com eBook Library
 IBM Software Construction Toolbox
 Microsoft RIA Development Center
 Destination .NET
XML error: not well-formed (invalid token) at line 43
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Google Hopes Chrome Will Help, Not Hurt Firefox
Remember Figlets? They're Back With Zend
Microsoft Readies an App Store Competitor?
Google: Chrome Browser Will Make Money
Sam Ramji: Microsoft's Man in Open Source
Google to Shake Up Browsers With Own Launch
Mozilla's Ubquity Mashup: For The Masses?
iPhone Users Just Want to Have Fun
Oops! I Fixed the Linux Kernel
Jim Zemlin: The New Center of Linux Gravity

Code Around C#'s Using Statement to Release Unmanaged Resources
Writing Functional Code with RDFa
BitLocker Brings Encryption to Windows Server 2008
Network Know-How: Exploring Network Algorithms
Create a Durable and Reliable WCF Service with MSMQ 4.0
The Baker's Dozen: 13 Tips for SQL Server 2008 and SSRS 2008
Book Excerpt: Microsoft Expression Blend Unleashed
Develop a Mobile RSS Feed the Easy Way
State of the Semantic Web: Know Where to Look
A 3D Exploration of the HTML Canvas Element

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Intel PDF: Virtualization Delivers Data Center Efficiency
Intel eBook: Managing the Evolving Data Center
Microsoft Article: BitLocker Brings Encryption to Windows Server 2008
Symantec eBook: The Guide to E-Mail Archiving and Management
Microsoft Article: RODCs Transform Branch Office Security
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
Avaya Article: Advancing the State of the Art in Customer Service
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Avaya Article: Avaya AE Services Provide Rapid Telephony Integration with Facebook
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Seminar: Efficiencies in Hardware/Software Virtualization
HP Webcast: Disaster Recovery Planning
Go Parallel Video: Performance and Threading Tools for Game Developers
HP Video: StorageWorks EVA4400 and Oracle
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
IBM TCO eKIT: Your IT Budget is Under Attack, Get in Control
IBM Energy Efficiency eKIT: Learn How to Reduce Costs
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt and free High-Performance SQL Code eBook
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
Microsoft Article: Silverlight Streaming--Free Video Hosting for All
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
HP Demo: StorageWorks EVA4400
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES