DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Trending

  • Optimizing Integration Workflows With Spark Structured Streaming and Cloud Services
  • Unlocking Data with Language: Real-World Applications of Text-to-SQL Interfaces
  • Driving DevOps With Smart, Scalable Testing
  • Building an AI/ML Data Lake With Apache Iceberg
  1. DZone
  2. Coding
  3. Frameworks
  4. Bean Validation in JAX-RS

Bean Validation in JAX-RS

Here's a quick overview of the JAX-RS specification, with exception handling and customizing default JAX-RS behavior.

By 
Abhishek Gupta user avatar
Abhishek Gupta
DZone Core CORE ·
Feb. 02, 16 · Analysis
Likes (8)
Comment
Save
Tweet
Share
21.5K Views

Join the DZone community and get the full member experience.

Join For Free

I have not dug into the Bean Validation specification into detail before, but one of the entries posted in the Payara issue tracker made me explore how the JAX-RS specification integrates/leverages the Bean Validation features.

Note: Bean Validation has been around since Java EE 6, but its integration with JAX-RS was materialized only in the latest (2.0) version (part of Java EE 7) 

In case you want to jump right into the code, you can fork it from GitHub

Quick Overview

I don’t want to dive into too many details:

  • JAX-RS supports declarative (as opposed to programmatic) validation using annotations from Bean Validation specification
  • It supports application of constraints to JAX-RS resource classes, method parameters (both request bodies as well as other components such as headers and URI parts like query parameters etc.), method return types and fields as well
@Path("users")
public class UsersResource {

    @HeaderParam("token")
    @Valid
    private Token token;

    @POST
    @Produces("application/json")
    @Consumes("application/json")
    public void save(@Valid User user){
        System.out.println("saved :: " + user);
    }

    @GET
    @Path("{name}")
    @Produces("application/json")
    public @Valid User get(@PathParam("name") String name){
        return new User(name, name+"@test.com");
    }
}

The JAX-RS spec also defines default behaviour for scenarios when the bean  validation constraints are violated

Exception Handling

JAX-RS implementations are forced to provide (by the spec) a default ExceptionMapper for handling bean validation constraint violation exceptions. It returns standard responses (HTTP 400/500) to clients based on some (default) rules outlined in the specification (see section 7.6 of the JAX-RS spec doc)

Customizing Default JAX-RS Behavior

The default JAX-RS behaviour can be overridden by providing your own (custom) Exception Mapper implementation.

@Provider
public class BeanValConstrainViolationExceptionMapper implements ExceptionMapper<ConstraintViolationException>{

    @Override
    public Response toResponse(ConstraintViolationException e) {
        System.out.println("BeanValConstrainViolationExceptionMapper in action");

        ConstraintViolation cv = (ConstraintViolation) e.getConstraintViolations().toArray()[0];
        //oh yeah... you need to shell out some $$$ !
        return Response.status(Response.Status.PAYMENT_REQUIRED)
                .entity(new ConstraintViolationEntity(cv.getMessage()))
                .build();
    }

}

Further Reading

  • I would encourage you to dig into Chapter 7 of the JAX-RS 2.0 specification document for deeper insight into this topic. It’s brief and to the point
  • Oh, and here is the link to the latest Bean Validation (1.1) spec doc

Cheers!

Spring Framework

Published at DZone with permission of Abhishek Gupta, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!