SlideShare a Scribd company logo
REQUEST
VALIDATION:SPRING
REST
Presented By Sabir Khan
Background
 Spring REST is not a standardized JAX-RS implementation and there doesn’t seem
an attempt to move to that direction either
 RESTeasy, Restlet, Jersey and ApacheCXF implement JAX-RS to different extents but
not Spring REST because of its background in Spring MVC
 Spring REST is a tweaked version of Spring MVC
 This presentation is about request bean validation at a @RestController
Why we need it?
 For a REST End Point – Its not guaranteed that client will always send a well formed
request
 Request Bean could be malformed in various ways like being empty string, null value
or not passable value to a particular type
 REST Entry Point need not to proceed if request is invalid and data sent is improper
 If request is invalid, REST Entry Point need to return an error response automatically
and service developers need not be tweaking service logic for data invalidity
 Validation needs to be segregated system component for maintainable flow and
readable code
What is Bean Validation?
 Bean validation is about validating a POJO’s fields for particular values
 Details about bean validation can be found at - http://beanvalidation.org/
 Its basically about specifying constraints on POJO fields
 At home page, its written – “Constrain once, validate everywhere”
 This validation might be needed in JavaSE or JavaEE
 Above link is simply a specification, its implementation needs to be provided and
specification is JSR-303, later improved to JSR-349
 One such implementation is provided by Apache, another by Hibernate and so on so
forth
 http://bval.apache.org/ & http://hibernate.org/validator/
Getting Started : Coding…Dependency
 First you need to include validation API implementations in your REST application. I have
not specified versions so it will get latest versions.
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
Coding…Enable Validation at Entry Point
 After including dependencies in application, you need to enable validation for your request bean at your entry point
 This can be achieved either by @Valid or @Validated annotation as shown below,
@RestController
@RequestMapping("/baseURL")
public class MyController {
@Autowired private Service service;
@RequestMapping(method = RequestMethod.POST, value = "/entryURL" , consumes=MediaType.APPLICATION_JSON_VALUE, produces
=MediaType.APPLICATION_JSON_VALUE )
public ResponseBean<...> getResponse( @Valid @RequestBody RequestBean request) {
/* Control comes here only if request satisfies all of your validations since @Valid is palced there */
/* service is a service instance that you would use to build a successful response */
}
}
@Valid is - import javax.validation.Valid;
Coding…Simple Validations
 After previous step, bean validation is enabled for POJO – RequestBean if a hit is made to that entry
point
 Now, you can go to RequestBean class and apply simple validations from either of the two dependencies
included in the project
 Most commonly used annotations are - @NotEmpty, @NotNull, @Email
 In these annotations ,you can specify custom messages for validator failures
 You can find many such annotations in - org.hibernate.validator.constraints package ( for hibernate jar ) &
javax.validation.constraints package ( for javax jar )
 Since you have applied , @Valid to @RequestBody at entry point, now your bean will automatically be
validated against these rules/annotations
 Control will go inside of entry point method if validation passes
 If validation fails, an exception be thrown–
org.springframework.web.bind.MethodArgumentNotValidException or
Coding…Exception Handler
 Since, you have enabled validation so exception – MethodArgumentNotValidException might be thrown for invalid requests
 System might have multiple services / End Points and developer shouldn’t be required to construct a response for each of these failure in
every service so you can have a Spring’s global application handler like below – Its just a sample , you can send a response as per your
need
@ControllerAdvice(value=“*.controller") -> this is basically controller package location
@Component
public class ApplicationExceptionHandler {
@ExceptionHandler
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseBean handle(MethodArgumentNotValidException exception){
StringBuilder messages = new StringBuilder();
ResponseBean response = new ResponseBean();
int count = 1;
for(ObjectError error:exception.getBindingResult().getAllErrors()){
messages.append(" "+count+"."+error.getDefaultMessage());
++count;
}
response.setResponse(“FAILURE”);
response.setErrorcode(400);
response.setMessage(messages.toString());
Coding…Complex Validations
 Sometimes, a simple validation rule or rules for each of the bean fields might not be enough i.e.
validation for each of the fields might not be independent from each other. Like – if you need any of the
25 fields to be @NotNull etc.
 For such situations, Spring gives you an option to write your own validator by implementing interface-
org.springframework.validation.Validator
public class MyValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return RequestBean.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {}
/* Write all your custom validations here */
/* For all validations, do specify messages to be passed on to user in errors
object*/
}
Coding…Complex Validations…Contd
 Abstract class - org.springframework.validation.ValidationUtils can be used to write validations like ,
ValidationUtils.rejectIfEmptyOrWhitespace(errors, “FIELD-1", "field.required"," FIELD-1 field is missing in
request body");
etc
 You can write complex validations using Java Reflection or By Using getters on RequestBean
 Java Reflection is flexible and you will not be required to change validator for bean field addition and
removal
 In validator, you might choose to log error messages on server side if errors.hasErrors() is true
Coding…Complex Validations…Contd
 Plugin Your validator to System : You have defined a custom validator but Spring doesn’t know about it
 You can write a global application initializer like below to tell framework about it i.e. register it ,
@ControllerAdvice(value=“*.controller") -> This is controller package
@Component
public class GlobalApplicationInitializer {
@InitBinder
public void globalInitBinder(WebDataBinder binder) {
binder.addValidators(new MyValidator());
}
}
Alternatively, you can define a validator @Bean in @Configuration and can use @Autowired instance in
addValidators method
Now your simple as well as custom validation both can be used on same bean.
@Valid Vs @Validated
There is another annotation @Validated provided by Spring -
org.springframework.validation.annotation.Validated that can be used other than -
javax.validation.Valid
@Validated supports validation groups and that is useful in multi step validations usually not useful for a
REST End Point but for a Web Form
So @Valid is standardized JEE annotation while @Validated is not.
Thank You !!
Thank You !!

More Related Content

PPTX
Request Validation In Spring Rest-Part2
PPTX
Java Custom Annotations- Part1
PPTX
25+ Reasons to use OmniFaces in JSF applications
PPTX
API Virtualization: Mocking on Steroids
PPT
Mastering OmniFaces - A Problem to Solution Approach
PPTX
Prince sttalkv5
PPTX
OmniFaces validators
PDF
Selenium Basics Tutorial
Request Validation In Spring Rest-Part2
Java Custom Annotations- Part1
25+ Reasons to use OmniFaces in JSF applications
API Virtualization: Mocking on Steroids
Mastering OmniFaces - A Problem to Solution Approach
Prince sttalkv5
OmniFaces validators
Selenium Basics Tutorial

What's hot (19)

PPTX
Breaking free from static abuse in test automation frameworks and using Sprin...
PDF
Selenium Handbook
PPTX
Automation Testing by Selenium Web Driver
DOCX
Selenium interview questions
PPT
Hybrid framework
DOC
Hybrid framework for test automation
PPT
Getting Started with Zend Framework
PDF
Selenium Overview
PDF
AngularJs Style Guide
PDF
1/3 : introduction to CDI - Antoine Sabot-Durand
PPT
Selenium Concepts
PDF
2/3 : CDI advanced - Antoine Sabot-Durand
PPTX
ATAGTR2017 Upgrading a mobile tester's weapons with advanced debugging
PPTX
An overview of selenium webdriver
PPTX
ASP.Net MVC 4 [Part - 2]
PPTX
Selenium WebDriver
PPTX
Selenium Interview Questions & Answers
PDF
Selenium Automation Testing Interview Questions And Answers
DOC
Resume
Breaking free from static abuse in test automation frameworks and using Sprin...
Selenium Handbook
Automation Testing by Selenium Web Driver
Selenium interview questions
Hybrid framework
Hybrid framework for test automation
Getting Started with Zend Framework
Selenium Overview
AngularJs Style Guide
1/3 : introduction to CDI - Antoine Sabot-Durand
Selenium Concepts
2/3 : CDI advanced - Antoine Sabot-Durand
ATAGTR2017 Upgrading a mobile tester's weapons with advanced debugging
An overview of selenium webdriver
ASP.Net MVC 4 [Part - 2]
Selenium WebDriver
Selenium Interview Questions & Answers
Selenium Automation Testing Interview Questions And Answers
Resume
Ad

Similar to Spring REST Request Validation (17)

PDF
JSRs 303 and 330 in Action
PDF
Spring Framework - Validation
PDF
PPTX
Mule soft esb – data validation best practices
PDF
JSR-303 Bean Validation API
PDF
Spring 3: What's New
PDF
From OOP to FP : the validation case
PDF
From OOP to FP: The validation case
PPTX
Flexible validation with Hibernate Validator 5.x.
PPT
My journey to use a validation framework
PPTX
Grails basics part2
PDF
SpringOne Tour: Spring Recipes: A Collection of Common-Sense Solutions
PPTX
Test your microservices with REST-Assured
PDF
Validation in Jakarta Struts 1.3
PDF
cbvalidation
PPTX
Mule ESB- Data Validation- Best Practices
PDF
Building+a+rest+api+with+spring
JSRs 303 and 330 in Action
Spring Framework - Validation
Mule soft esb – data validation best practices
JSR-303 Bean Validation API
Spring 3: What's New
From OOP to FP : the validation case
From OOP to FP: The validation case
Flexible validation with Hibernate Validator 5.x.
My journey to use a validation framework
Grails basics part2
SpringOne Tour: Spring Recipes: A Collection of Common-Sense Solutions
Test your microservices with REST-Assured
Validation in Jakarta Struts 1.3
cbvalidation
Mule ESB- Data Validation- Best Practices
Building+a+rest+api+with+spring
Ad

Recently uploaded (20)

PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPT
Teaching material agriculture food technology
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Spectroscopy.pptx food analysis technology
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
KodekX | Application Modernization Development
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Teaching material agriculture food technology
Diabetes mellitus diagnosis method based random forest with bat algorithm
Digital-Transformation-Roadmap-for-Companies.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
20250228 LYD VKU AI Blended-Learning.pptx
Big Data Technologies - Introduction.pptx
Spectroscopy.pptx food analysis technology
Unlocking AI with Model Context Protocol (MCP)
Reach Out and Touch Someone: Haptics and Empathic Computing
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
The Rise and Fall of 3GPP – Time for a Sabbatical?
Encapsulation_ Review paper, used for researhc scholars
Building Integrated photovoltaic BIPV_UPV.pdf
KodekX | Application Modernization Development
NewMind AI Weekly Chronicles - August'25 Week I
Machine learning based COVID-19 study performance prediction
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx

Spring REST Request Validation

  • 2. Background  Spring REST is not a standardized JAX-RS implementation and there doesn’t seem an attempt to move to that direction either  RESTeasy, Restlet, Jersey and ApacheCXF implement JAX-RS to different extents but not Spring REST because of its background in Spring MVC  Spring REST is a tweaked version of Spring MVC  This presentation is about request bean validation at a @RestController
  • 3. Why we need it?  For a REST End Point – Its not guaranteed that client will always send a well formed request  Request Bean could be malformed in various ways like being empty string, null value or not passable value to a particular type  REST Entry Point need not to proceed if request is invalid and data sent is improper  If request is invalid, REST Entry Point need to return an error response automatically and service developers need not be tweaking service logic for data invalidity  Validation needs to be segregated system component for maintainable flow and readable code
  • 4. What is Bean Validation?  Bean validation is about validating a POJO’s fields for particular values  Details about bean validation can be found at - http://beanvalidation.org/  Its basically about specifying constraints on POJO fields  At home page, its written – “Constrain once, validate everywhere”  This validation might be needed in JavaSE or JavaEE  Above link is simply a specification, its implementation needs to be provided and specification is JSR-303, later improved to JSR-349  One such implementation is provided by Apache, another by Hibernate and so on so forth  http://bval.apache.org/ & http://hibernate.org/validator/
  • 5. Getting Started : Coding…Dependency  First you need to include validation API implementations in your REST application. I have not specified versions so it will get latest versions. <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> </dependency>
  • 6. Coding…Enable Validation at Entry Point  After including dependencies in application, you need to enable validation for your request bean at your entry point  This can be achieved either by @Valid or @Validated annotation as shown below, @RestController @RequestMapping("/baseURL") public class MyController { @Autowired private Service service; @RequestMapping(method = RequestMethod.POST, value = "/entryURL" , consumes=MediaType.APPLICATION_JSON_VALUE, produces =MediaType.APPLICATION_JSON_VALUE ) public ResponseBean<...> getResponse( @Valid @RequestBody RequestBean request) { /* Control comes here only if request satisfies all of your validations since @Valid is palced there */ /* service is a service instance that you would use to build a successful response */ } } @Valid is - import javax.validation.Valid;
  • 7. Coding…Simple Validations  After previous step, bean validation is enabled for POJO – RequestBean if a hit is made to that entry point  Now, you can go to RequestBean class and apply simple validations from either of the two dependencies included in the project  Most commonly used annotations are - @NotEmpty, @NotNull, @Email  In these annotations ,you can specify custom messages for validator failures  You can find many such annotations in - org.hibernate.validator.constraints package ( for hibernate jar ) & javax.validation.constraints package ( for javax jar )  Since you have applied , @Valid to @RequestBody at entry point, now your bean will automatically be validated against these rules/annotations  Control will go inside of entry point method if validation passes  If validation fails, an exception be thrown– org.springframework.web.bind.MethodArgumentNotValidException or
  • 8. Coding…Exception Handler  Since, you have enabled validation so exception – MethodArgumentNotValidException might be thrown for invalid requests  System might have multiple services / End Points and developer shouldn’t be required to construct a response for each of these failure in every service so you can have a Spring’s global application handler like below – Its just a sample , you can send a response as per your need @ControllerAdvice(value=“*.controller") -> this is basically controller package location @Component public class ApplicationExceptionHandler { @ExceptionHandler @ResponseBody @ResponseStatus(HttpStatus.BAD_REQUEST) public ResponseBean handle(MethodArgumentNotValidException exception){ StringBuilder messages = new StringBuilder(); ResponseBean response = new ResponseBean(); int count = 1; for(ObjectError error:exception.getBindingResult().getAllErrors()){ messages.append(" "+count+"."+error.getDefaultMessage()); ++count; } response.setResponse(“FAILURE”); response.setErrorcode(400); response.setMessage(messages.toString());
  • 9. Coding…Complex Validations  Sometimes, a simple validation rule or rules for each of the bean fields might not be enough i.e. validation for each of the fields might not be independent from each other. Like – if you need any of the 25 fields to be @NotNull etc.  For such situations, Spring gives you an option to write your own validator by implementing interface- org.springframework.validation.Validator public class MyValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return RequestBean.class.isAssignableFrom(clazz); } @Override public void validate(Object target, Errors errors) {} /* Write all your custom validations here */ /* For all validations, do specify messages to be passed on to user in errors object*/ }
  • 10. Coding…Complex Validations…Contd  Abstract class - org.springframework.validation.ValidationUtils can be used to write validations like , ValidationUtils.rejectIfEmptyOrWhitespace(errors, “FIELD-1", "field.required"," FIELD-1 field is missing in request body"); etc  You can write complex validations using Java Reflection or By Using getters on RequestBean  Java Reflection is flexible and you will not be required to change validator for bean field addition and removal  In validator, you might choose to log error messages on server side if errors.hasErrors() is true
  • 11. Coding…Complex Validations…Contd  Plugin Your validator to System : You have defined a custom validator but Spring doesn’t know about it  You can write a global application initializer like below to tell framework about it i.e. register it , @ControllerAdvice(value=“*.controller") -> This is controller package @Component public class GlobalApplicationInitializer { @InitBinder public void globalInitBinder(WebDataBinder binder) { binder.addValidators(new MyValidator()); } } Alternatively, you can define a validator @Bean in @Configuration and can use @Autowired instance in addValidators method Now your simple as well as custom validation both can be used on same bean.
  • 12. @Valid Vs @Validated There is another annotation @Validated provided by Spring - org.springframework.validation.annotation.Validated that can be used other than - javax.validation.Valid @Validated supports validation groups and that is useful in multi step validations usually not useful for a REST End Point but for a Web Form So @Valid is standardized JEE annotation while @Validated is not.

Editor's Notes

  • #2: NOTE: To change the image on this slide, select the picture and delete it. Then click the Pictures icon in the placeholder to insert your own image.