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

What's hot

Breaking free from static abuse in test automation frameworks and using Sprin...
Breaking free from static abuse in test automation frameworks and using Sprin...Breaking free from static abuse in test automation frameworks and using Sprin...
Breaking free from static abuse in test automation frameworks and using Sprin...
Abhijeet Vaikar
 
Selenium interview questions
Selenium interview questionsSelenium interview questions
Selenium interview questions
girichinna27
 
Hybrid framework for test automation
Hybrid framework for test automationHybrid framework for test automation
Hybrid framework for test automationsrivinayak
 
Getting Started with Zend Framework
Getting Started with Zend FrameworkGetting Started with Zend Framework
Getting Started with Zend Framework
Juan Antonio
 
Selenium Overview
Selenium OverviewSelenium Overview
Selenium Overview
Abhijeet Vaikar
 
AngularJs Style Guide
AngularJs Style GuideAngularJs Style Guide
AngularJs Style GuideChiew Carol
 
1/3 : introduction to CDI - Antoine Sabot-Durand
1/3 : introduction to CDI - Antoine Sabot-Durand1/3 : introduction to CDI - Antoine Sabot-Durand
1/3 : introduction to CDI - Antoine Sabot-Durand
SOAT
 
2/3 : CDI advanced - Antoine Sabot-Durand
2/3 : CDI advanced - Antoine Sabot-Durand2/3 : CDI advanced - Antoine Sabot-Durand
2/3 : CDI advanced - Antoine Sabot-Durand
SOAT
 
ATAGTR2017 Upgrading a mobile tester's weapons with advanced debugging
ATAGTR2017 Upgrading a mobile tester's weapons with advanced debuggingATAGTR2017 Upgrading a mobile tester's weapons with advanced debugging
ATAGTR2017 Upgrading a mobile tester's weapons with advanced debugging
Agile Testing Alliance
 
An overview of selenium webdriver
An overview of selenium webdriverAn overview of selenium webdriver
An overview of selenium webdriver
Anuraj S.L
 
ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]
Mohamed Abdeen
 
Selenium WebDriver
Selenium WebDriverSelenium WebDriver
Selenium WebDriver
Yuriy Bezgachnyuk
 
Selenium Interview Questions & Answers
Selenium Interview Questions & AnswersSelenium Interview Questions & Answers
Selenium Interview Questions & Answers
Techcanvass
 
Selenium Automation Testing Interview Questions And Answers
Selenium Automation Testing Interview Questions And AnswersSelenium Automation Testing Interview Questions And Answers
Selenium Automation Testing Interview Questions And Answers
Ajit Jadhav
 

What's hot (19)

Breaking free from static abuse in test automation frameworks and using Sprin...
Breaking free from static abuse in test automation frameworks and using Sprin...Breaking free from static abuse in test automation frameworks and using Sprin...
Breaking free from static abuse in test automation frameworks and using Sprin...
 
Selenium Handbook
Selenium HandbookSelenium Handbook
Selenium Handbook
 
Automation Testing by Selenium Web Driver
Automation Testing by Selenium Web DriverAutomation Testing by Selenium Web Driver
Automation Testing by Selenium Web Driver
 
Selenium interview questions
Selenium interview questionsSelenium interview questions
Selenium interview questions
 
Hybrid framework
Hybrid frameworkHybrid framework
Hybrid framework
 
Hybrid framework for test automation
Hybrid framework for test automationHybrid framework for test automation
Hybrid framework for test automation
 
Getting Started with Zend Framework
Getting Started with Zend FrameworkGetting Started with Zend Framework
Getting Started with Zend Framework
 
Selenium Overview
Selenium OverviewSelenium Overview
Selenium Overview
 
AngularJs Style Guide
AngularJs Style GuideAngularJs Style Guide
AngularJs Style Guide
 
1/3 : introduction to CDI - Antoine Sabot-Durand
1/3 : introduction to CDI - Antoine Sabot-Durand1/3 : introduction to CDI - Antoine Sabot-Durand
1/3 : introduction to CDI - Antoine Sabot-Durand
 
Selenium Concepts
Selenium ConceptsSelenium Concepts
Selenium Concepts
 
2/3 : CDI advanced - Antoine Sabot-Durand
2/3 : CDI advanced - Antoine Sabot-Durand2/3 : CDI advanced - Antoine Sabot-Durand
2/3 : CDI advanced - Antoine Sabot-Durand
 
ATAGTR2017 Upgrading a mobile tester's weapons with advanced debugging
ATAGTR2017 Upgrading a mobile tester's weapons with advanced debuggingATAGTR2017 Upgrading a mobile tester's weapons with advanced debugging
ATAGTR2017 Upgrading a mobile tester's weapons with advanced debugging
 
An overview of selenium webdriver
An overview of selenium webdriverAn overview of selenium webdriver
An overview of selenium webdriver
 
ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]
 
Selenium WebDriver
Selenium WebDriverSelenium WebDriver
Selenium WebDriver
 
Selenium Interview Questions & Answers
Selenium Interview Questions & AnswersSelenium Interview Questions & Answers
Selenium Interview Questions & Answers
 
Selenium Automation Testing Interview Questions And Answers
Selenium Automation Testing Interview Questions And AnswersSelenium Automation Testing Interview Questions And Answers
Selenium Automation Testing Interview Questions And Answers
 
Resume
ResumeResume
Resume
 

Similar to Spring REST Request Validation

Validation in Jakarta Struts 1.3
Validation in Jakarta Struts 1.3Validation in Jakarta Struts 1.3
Validation in Jakarta Struts 1.3
Ilio Catallo
 
SpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptx
SUFYAN SATTAR
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
Vinay Kumar
 
Building Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in Rails
Jim Jeffers
 
Online Form Submission App
Online Form Submission AppOnline Form Submission App
Online Form Submission AppPeeyush Ranjan
 
InterConnect 2016 Java EE 7 Overview (PEJ-5296)
InterConnect 2016 Java EE 7 Overview (PEJ-5296)InterConnect 2016 Java EE 7 Overview (PEJ-5296)
InterConnect 2016 Java EE 7 Overview (PEJ-5296)
Kevin Sutter
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony Container
Diego Lewin
 
Multiple Submit Button Test App
Multiple Submit Button Test AppMultiple Submit Button Test App
Multiple Submit Button Test AppPeeyush Ranjan
 
Servlet LifeCycle Demo App
Servlet LifeCycle Demo  AppServlet LifeCycle Demo  App
Servlet LifeCycle Demo AppPeeyush Ranjan
 
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
Raffaele Chiocca
 
Spring training
Spring trainingSpring training
Spring training
TechFerry
 
Servlet to Spring: Internal Understanding
Servlet to Spring: Internal UnderstandingServlet to Spring: Internal Understanding
Servlet to Spring: Internal Understanding
Knoldus Inc.
 
ASP.NET Core Web API documentation web application
ASP.NET Core Web API documentation web applicationASP.NET Core Web API documentation web application
ASP.NET Core Web API documentation web application
AMARAAHMED7
 
CTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVCCTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVC
Barry Gervin
 
Haj 4328-java ee 7 overview
Haj 4328-java ee 7 overviewHaj 4328-java ee 7 overview
Haj 4328-java ee 7 overview
Kevin Sutter
 
Spring security jwt tutorial toptal
Spring security jwt tutorial   toptalSpring security jwt tutorial   toptal
Spring security jwt tutorial toptal
jbsysatm
 
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Gavin Pickin
 

Similar to Spring REST Request Validation (20)

Validation in Jakarta Struts 1.3
Validation in Jakarta Struts 1.3Validation in Jakarta Struts 1.3
Validation in Jakarta Struts 1.3
 
SpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptx
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
 
Building Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in Rails
 
Validation controls ASP .NET
Validation controls ASP .NETValidation controls ASP .NET
Validation controls ASP .NET
 
Online Form Submission App
Online Form Submission AppOnline Form Submission App
Online Form Submission App
 
InterConnect 2016 Java EE 7 Overview (PEJ-5296)
InterConnect 2016 Java EE 7 Overview (PEJ-5296)InterConnect 2016 Java EE 7 Overview (PEJ-5296)
InterConnect 2016 Java EE 7 Overview (PEJ-5296)
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony Container
 
Multiple Submit Button Test App
Multiple Submit Button Test AppMultiple Submit Button Test App
Multiple Submit Button Test App
 
Servlet LifeCycle Demo App
Servlet LifeCycle Demo  AppServlet LifeCycle Demo  App
Servlet LifeCycle Demo App
 
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
 
Spring training
Spring trainingSpring training
Spring training
 
Servlet to Spring: Internal Understanding
Servlet to Spring: Internal UnderstandingServlet to Spring: Internal Understanding
Servlet to Spring: Internal Understanding
 
ASP.NET Core Web API documentation web application
ASP.NET Core Web API documentation web applicationASP.NET Core Web API documentation web application
ASP.NET Core Web API documentation web application
 
JEE5 New Features
JEE5 New FeaturesJEE5 New Features
JEE5 New Features
 
CTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVCCTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVC
 
Haj 4328-java ee 7 overview
Haj 4328-java ee 7 overviewHaj 4328-java ee 7 overview
Haj 4328-java ee 7 overview
 
Spring security jwt tutorial toptal
Spring security jwt tutorial   toptalSpring security jwt tutorial   toptal
Spring security jwt tutorial toptal
 
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin Pickin
 
Jdbc
JdbcJdbc
Jdbc
 

Recently uploaded

FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 

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

  1. 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.