SlideShare une entreprise Scribd logo
1  sur  12
REQUEST
VALIDATION:SPRING
REST-PART 2
Presented By Sabir Khan
Background
 Please refer my earlier presentation to get basics,
https://www.slideshare.net/MohammadSabirKhan/spring-rest-request-validation
 Part -1 presentation highlights use of @Valid annotation
 With @Valid annotation, you can validate Java POJOs i.e. specific to Spring REST, it
would be @RequestBody
 If you simply place @Valid & @NotEmpty to a GET request @RequestParam or
@PathVariable, it wouldn’t work i.e. it will have no effect – validator wouldn’t be
invoked
 Directly placing JSR annotations for method parameters was not supported in bean
validation 1.0 ( JSR – 303 ) and support started from bean validation 1.1 ( JSR –
349)
 So you have to make sure that you are using JSR – 349 implementation before using
this feature
Why we need it?
 For a REST End Point – Its not guaranteed that client will always send a well formed
request
 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
 As described in previous slide, you will have to convert method parameters into a POJO
to validate with @Valid, we are trying to avoid it and directly process validation
annotations placed on method signatures for simple arguments like String etc.
 Lots of confusion is out there on Internet because of change of bean validation
standards, types of validations supported and various techniques to invoke validator
Getting Started : Coding…Dependency
 First you need to include validation API standard and implementations in your REST application
that supports JSR – 349.
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.3.4.Final</version>
</dependency>
Getting Started : Coding…Dependency…Contd
 Out of those two dependencies, validation-api-1.1.0.Final.jar is a reference to JSR –
349 while hibernate-validator-5.3.4.Final.jar is a JSR-349 implementation
 Hibernate JAR has nothing to do with hibernate ORM implementation, its simply a
bean validation implementation and can be used in non – hibernate environments.
Here we are trying to use for Spring REST service.
 If you are using Spring Boot, these two dependencies will already be there as part of
below dependency and not required to include separately.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Coding…Enable Method Validation
 Processing validation annotations as part of method signatures are not
enabled by default.
 You need to tell Spring Framework to process @Email, @NotNull,
@NotEmpty annotations included in method signatures directly without
@Valid annotation
 This is achieved in two steps,
1. Place @Validated -
org.springframework.validation.annotation.Validated at your
controller class, like ,
@RestController
@RequestMapping("/…")
@Validated
Coding…Enable Method Validation…Contd
2. Place these two beans in your Spring Configuration i.e. in
@Configuration class available for application
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
MethodValidationPostProcessor mvProcessor = new MethodValidationPostProcessor();
mvProcessor.setValidator(validator());
return mvProcessor;
}
@Bean
public LocalValidatorFactoryBean validator(){
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.setProviderClass(HibernateValidator.class);
validator.afterPropertiesSet();
return validator;
}
Coding…Enable Method Validation…Contd
 You have to note that Spring has its own validators and we have to somehow tell
Spring that method level annotation processing is enabled and which validator
factory to use to process those validations ( Its Hibernate implementation in our
case )
 Hibernate validator documentation says that you can invoke their validator via some
AOP kind of mechanism and Spring provides that mechanism , refer JIRA -
https://jira.spring.io/browse/SPR-8199 to know a bit more
 In Absence of this in build mechanism, you will have to invoke validator on your own
as described in - https://github.com/gunnarmorling/methodvalidation-integration
 Anyway, now you are set to validate your @RequestParam & @PathVariable directly
in method signatures
Coding…Validate
 Now , you can do below
@RequestMapping(method = RequestMethod.GET, value = "/testValidated" , consumes=MediaType.APPLICATION_JSON_VALUE, produces
=MediaType.APPLICATION_JSON_VALUE )
public ResponseBean<String> testValidated( @Email(message="email RequestParam is not a valid email address") @NotEmpty(message="email
RequestParam is empty") @RequestParam("email") String email ){
ResponseBean<String> response = new ResponseBean<>();
……
return response;
}
Above code tells that for @RequestParam(“email”) – validate if it’s a valid email address and if its not empty String
You can externalize message Strings
No need to place @Valid or @Validated in method signature
You can use other available annotations as per your need
Coding…Exception Handler
 In part – 1 of presentation, we saw that @Valid throws – MethodArgumentNotValidException but @Validated throws a different exception –
ConstraintViolationException so we will have to write a handler for this exception too.
@RestControllerAdvice(value=“*.controller") -> this is basically controller package location
public class ApplicationExceptionHandler {
@ExceptionHandler
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseBean handle(ConstraintViolationException exception){
 StringBuilder messages = new StringBuilder();
 ResponseBean response = new ResponseBean();
 int count = 1;
 for(ConstraintViolation<?> violation:exception.getConstraintViolations()){
 messages.append(" "+count+"."+violation.getMessage());
 ++count;
 }
 response.setResponse(Constants.FAILURE);
 response.setErrorcode(Constants.ERROR_CODE_BAD_REQUEST);
 response.setMessage(messages.toString());
 return response;
}
}
ResponseBean is my application specific class that I wrote my own , you can have your own.
This handler will automatically be called if validation fails and response returned to your client.
References
1. https://github.com/gunnarmorling/methodvalidation-integration
2. http://apprize.info/javascript/wrox/16.html
3. https://jira.spring.io/browse/SPR-8199
4. https://dzone.com/articles/method-validation-spring-31
5. http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#chapter-method-constraints
Thank You !!
Thank You !!

Contenu connexe

Tendances

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
 
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 debuggingAgile Testing Alliance
 
Selenium interview questions
Selenium interview questionsSelenium interview questions
Selenium interview questionsgirichinna27
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentChui-Wen Chiu
 
Getting Started with Zend Framework
Getting Started with Zend FrameworkGetting Started with Zend Framework
Getting Started with Zend FrameworkJuan Antonio
 
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-DurandSOAT
 
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-DurandSOAT
 
Test Coverage for Your WP REST API Project
Test Coverage for Your WP REST API ProjectTest Coverage for Your WP REST API Project
Test Coverage for Your WP REST API ProjectPantheon
 
3/3 : The path to CDI 2.0 - Antoine Sabot-Durand
3/3 : The path to CDI 2.0 - Antoine Sabot-Durand3/3 : The path to CDI 2.0 - Antoine Sabot-Durand
3/3 : The path to CDI 2.0 - Antoine Sabot-DurandSOAT
 
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
 
Hybrid framework for test automation
Hybrid framework for test automationHybrid framework for test automation
Hybrid framework for test automationsrivinayak
 
Mock Server Using WireMock
Mock Server Using WireMockMock Server Using WireMock
Mock Server Using WireMockGlobant
 
Performance Testing REST APIs
Performance Testing REST APIsPerformance Testing REST APIs
Performance Testing REST APIsJason Weden
 

Tendances (19)

Automation Testing by Selenium Web Driver
Automation Testing by Selenium Web DriverAutomation Testing by Selenium Web Driver
Automation Testing by Selenium Web Driver
 
Selenium Handbook
Selenium HandbookSelenium Handbook
Selenium Handbook
 
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
 
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
 
Selenium interview questions
Selenium interview questionsSelenium interview questions
Selenium interview questions
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component Development
 
Getting Started with Zend Framework
Getting Started with Zend FrameworkGetting Started with Zend Framework
Getting Started with Zend Framework
 
Hybrid framework
Hybrid frameworkHybrid framework
Hybrid framework
 
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
 
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
 
Selenium Overview
Selenium OverviewSelenium Overview
Selenium Overview
 
Test Coverage for Your WP REST API Project
Test Coverage for Your WP REST API ProjectTest Coverage for Your WP REST API Project
Test Coverage for Your WP REST API Project
 
3/3 : The path to CDI 2.0 - Antoine Sabot-Durand
3/3 : The path to CDI 2.0 - Antoine Sabot-Durand3/3 : The path to CDI 2.0 - Antoine Sabot-Durand
3/3 : The path to CDI 2.0 - Antoine Sabot-Durand
 
ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]
 
Hybrid framework for test automation
Hybrid framework for test automationHybrid framework for test automation
Hybrid framework for test automation
 
Mock Server Using WireMock
Mock Server Using WireMockMock Server Using WireMock
Mock Server Using WireMock
 
Jsf
JsfJsf
Jsf
 
Performance Testing REST APIs
Performance Testing REST APIsPerformance Testing REST APIs
Performance Testing REST APIs
 
Selenium WebDriver
Selenium WebDriverSelenium WebDriver
Selenium WebDriver
 

Similaire à Request Validation In Spring Rest-Part2

Api testing bible using postman
Api testing bible using postmanApi testing bible using postman
Api testing bible using postmanAbhishek Saxena
 
SpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSUFYAN SATTAR
 
Modelling RESTful applications – Why should I not use verbs in REST url
Modelling RESTful applications – Why should I not use verbs in REST urlModelling RESTful applications – Why should I not use verbs in REST url
Modelling RESTful applications – Why should I not use verbs in REST urlXebia IT Architects
 
Spring security jwt tutorial toptal
Spring security jwt tutorial   toptalSpring security jwt tutorial   toptal
Spring security jwt tutorial toptaljbsysatm
 
OAuth Authorization flows in salesforce
OAuth Authorization flows in salesforceOAuth Authorization flows in salesforce
OAuth Authorization flows in salesforceKishore B T
 
Hackazon realistic e-commerce Hack platform
Hackazon realistic e-commerce Hack platformHackazon realistic e-commerce Hack platform
Hackazon realistic e-commerce Hack platformIhor Uzhvenko
 
ForwardJS 2017 - Fullstack end-to-end Test Automation with node.js
ForwardJS 2017 -  Fullstack end-to-end Test Automation with node.jsForwardJS 2017 -  Fullstack end-to-end Test Automation with node.js
ForwardJS 2017 - Fullstack end-to-end Test Automation with node.jsMek Srunyu Stittri
 
A Practical Guide to Automating End-to-End API Testing
A Practical Guide to Automating End-to-End API TestingA Practical Guide to Automating End-to-End API Testing
A Practical Guide to Automating End-to-End API TestingpCloudy
 
API Check Overview - Rigor Monitoring
API Check Overview - Rigor MonitoringAPI Check Overview - Rigor Monitoring
API Check Overview - Rigor MonitoringAnthony Ferrari
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depthVinay Kumar
 
Spring certification-mock-exam
Spring certification-mock-examSpring certification-mock-exam
Spring certification-mock-examdmz networks
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with SpringJoshua Long
 
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...RightScale
 
AAD B2C custom policies
AAD B2C custom policiesAAD B2C custom policies
AAD B2C custom policiesRory Braybrook
 
Indic threads delhi13-rest-anirudh
Indic threads delhi13-rest-anirudhIndic threads delhi13-rest-anirudh
Indic threads delhi13-rest-anirudhAnirudh Bhatnagar
 
My journey to use a validation framework
My journey to use a validation frameworkMy journey to use a validation framework
My journey to use a validation frameworksaqibsarwar
 
Open sap ui51_week_2_unit_3_acdt_exercises
Open sap ui51_week_2_unit_3_acdt_exercisesOpen sap ui51_week_2_unit_3_acdt_exercises
Open sap ui51_week_2_unit_3_acdt_exercisesvikram sukumar
 

Similaire à Request Validation In Spring Rest-Part2 (20)

Api testing bible using postman
Api testing bible using postmanApi testing bible using postman
Api testing bible using postman
 
SpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptx
 
Modelling RESTful applications – Why should I not use verbs in REST url
Modelling RESTful applications – Why should I not use verbs in REST urlModelling RESTful applications – Why should I not use verbs in REST url
Modelling RESTful applications – Why should I not use verbs in REST url
 
Spring security jwt tutorial toptal
Spring security jwt tutorial   toptalSpring security jwt tutorial   toptal
Spring security jwt tutorial toptal
 
OAuth Authorization flows in salesforce
OAuth Authorization flows in salesforceOAuth Authorization flows in salesforce
OAuth Authorization flows in salesforce
 
Hackazon realistic e-commerce Hack platform
Hackazon realistic e-commerce Hack platformHackazon realistic e-commerce Hack platform
Hackazon realistic e-commerce Hack platform
 
ForwardJS 2017 - Fullstack end-to-end Test Automation with node.js
ForwardJS 2017 -  Fullstack end-to-end Test Automation with node.jsForwardJS 2017 -  Fullstack end-to-end Test Automation with node.js
ForwardJS 2017 - Fullstack end-to-end Test Automation with node.js
 
A Practical Guide to Automating End-to-End API Testing
A Practical Guide to Automating End-to-End API TestingA Practical Guide to Automating End-to-End API Testing
A Practical Guide to Automating End-to-End API Testing
 
API Check Overview - Rigor Monitoring
API Check Overview - Rigor MonitoringAPI Check Overview - Rigor Monitoring
API Check Overview - Rigor Monitoring
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
 
Spring certification-mock-exam
Spring certification-mock-examSpring certification-mock-exam
Spring certification-mock-exam
 
Grails Advanced
Grails Advanced Grails Advanced
Grails Advanced
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...
 
AAD B2C custom policies
AAD B2C custom policiesAAD B2C custom policies
AAD B2C custom policies
 
Indic threads delhi13-rest-anirudh
Indic threads delhi13-rest-anirudhIndic threads delhi13-rest-anirudh
Indic threads delhi13-rest-anirudh
 
My journey to use a validation framework
My journey to use a validation frameworkMy journey to use a validation framework
My journey to use a validation framework
 
Open sap ui51_week_2_unit_3_acdt_exercises
Open sap ui51_week_2_unit_3_acdt_exercisesOpen sap ui51_week_2_unit_3_acdt_exercises
Open sap ui51_week_2_unit_3_acdt_exercises
 
Api testing
Api testingApi testing
Api testing
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 

Dernier

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 

Dernier (20)

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 

Request Validation In Spring Rest-Part2

  • 2. Background  Please refer my earlier presentation to get basics, https://www.slideshare.net/MohammadSabirKhan/spring-rest-request-validation  Part -1 presentation highlights use of @Valid annotation  With @Valid annotation, you can validate Java POJOs i.e. specific to Spring REST, it would be @RequestBody  If you simply place @Valid & @NotEmpty to a GET request @RequestParam or @PathVariable, it wouldn’t work i.e. it will have no effect – validator wouldn’t be invoked  Directly placing JSR annotations for method parameters was not supported in bean validation 1.0 ( JSR – 303 ) and support started from bean validation 1.1 ( JSR – 349)  So you have to make sure that you are using JSR – 349 implementation before using this feature
  • 3. Why we need it?  For a REST End Point – Its not guaranteed that client will always send a well formed request  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  As described in previous slide, you will have to convert method parameters into a POJO to validate with @Valid, we are trying to avoid it and directly process validation annotations placed on method signatures for simple arguments like String etc.  Lots of confusion is out there on Internet because of change of bean validation standards, types of validations supported and various techniques to invoke validator
  • 4. Getting Started : Coding…Dependency  First you need to include validation API standard and implementations in your REST application that supports JSR – 349. <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.3.4.Final</version> </dependency>
  • 5. Getting Started : Coding…Dependency…Contd  Out of those two dependencies, validation-api-1.1.0.Final.jar is a reference to JSR – 349 while hibernate-validator-5.3.4.Final.jar is a JSR-349 implementation  Hibernate JAR has nothing to do with hibernate ORM implementation, its simply a bean validation implementation and can be used in non – hibernate environments. Here we are trying to use for Spring REST service.  If you are using Spring Boot, these two dependencies will already be there as part of below dependency and not required to include separately. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
  • 6. Coding…Enable Method Validation  Processing validation annotations as part of method signatures are not enabled by default.  You need to tell Spring Framework to process @Email, @NotNull, @NotEmpty annotations included in method signatures directly without @Valid annotation  This is achieved in two steps, 1. Place @Validated - org.springframework.validation.annotation.Validated at your controller class, like , @RestController @RequestMapping("/…") @Validated
  • 7. Coding…Enable Method Validation…Contd 2. Place these two beans in your Spring Configuration i.e. in @Configuration class available for application @Bean public MethodValidationPostProcessor methodValidationPostProcessor() { MethodValidationPostProcessor mvProcessor = new MethodValidationPostProcessor(); mvProcessor.setValidator(validator()); return mvProcessor; } @Bean public LocalValidatorFactoryBean validator(){ LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.setProviderClass(HibernateValidator.class); validator.afterPropertiesSet(); return validator; }
  • 8. Coding…Enable Method Validation…Contd  You have to note that Spring has its own validators and we have to somehow tell Spring that method level annotation processing is enabled and which validator factory to use to process those validations ( Its Hibernate implementation in our case )  Hibernate validator documentation says that you can invoke their validator via some AOP kind of mechanism and Spring provides that mechanism , refer JIRA - https://jira.spring.io/browse/SPR-8199 to know a bit more  In Absence of this in build mechanism, you will have to invoke validator on your own as described in - https://github.com/gunnarmorling/methodvalidation-integration  Anyway, now you are set to validate your @RequestParam & @PathVariable directly in method signatures
  • 9. Coding…Validate  Now , you can do below @RequestMapping(method = RequestMethod.GET, value = "/testValidated" , consumes=MediaType.APPLICATION_JSON_VALUE, produces =MediaType.APPLICATION_JSON_VALUE ) public ResponseBean<String> testValidated( @Email(message="email RequestParam is not a valid email address") @NotEmpty(message="email RequestParam is empty") @RequestParam("email") String email ){ ResponseBean<String> response = new ResponseBean<>(); …… return response; } Above code tells that for @RequestParam(“email”) – validate if it’s a valid email address and if its not empty String You can externalize message Strings No need to place @Valid or @Validated in method signature You can use other available annotations as per your need
  • 10. Coding…Exception Handler  In part – 1 of presentation, we saw that @Valid throws – MethodArgumentNotValidException but @Validated throws a different exception – ConstraintViolationException so we will have to write a handler for this exception too. @RestControllerAdvice(value=“*.controller") -> this is basically controller package location public class ApplicationExceptionHandler { @ExceptionHandler @ResponseBody @ResponseStatus(HttpStatus.BAD_REQUEST) public ResponseBean handle(ConstraintViolationException exception){  StringBuilder messages = new StringBuilder();  ResponseBean response = new ResponseBean();  int count = 1;  for(ConstraintViolation<?> violation:exception.getConstraintViolations()){  messages.append(" "+count+"."+violation.getMessage());  ++count;  }  response.setResponse(Constants.FAILURE);  response.setErrorcode(Constants.ERROR_CODE_BAD_REQUEST);  response.setMessage(messages.toString());  return response; } } ResponseBean is my application specific class that I wrote my own , you can have your own. This handler will automatically be called if validation fails and response returned to your client.
  • 11. References 1. https://github.com/gunnarmorling/methodvalidation-integration 2. http://apprize.info/javascript/wrox/16.html 3. https://jira.spring.io/browse/SPR-8199 4. https://dzone.com/articles/method-validation-spring-31 5. http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#chapter-method-constraints

Notes de l'éditeur

  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.