Adding additional HTTP headers with JAX-RS and Bean Validation

A JAX-RS resource with input validation:


@Stateless
@Path("ping")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public class PingResource {

    @GET
    public String ping() {
        System.out.println(".");
        return "Enjoy Jakarta EE 8!";
    }

    @POST
    public void save(@Size(min = 2, max = 3) String ping) {
    }
}    

and installed ExceptionMapper

import java.util.stream.Collectors;
import javax.validation.ConstraintViolationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class ContraintViolationMapper implements ExceptionMapper<ConstraintViolationException> {

    @Override
    public Response toResponse(ConstraintViolationException exception) {
        String messages = exception.getConstraintViolations().stream().
                map(v -> v.getMessage()).
                collect(Collectors.joining(","));
        return Response.status(400).header("reason", messages).build();
    }

}

...will return additional information in header on each contraint violation.

A failed input validation: curl -XPOST -i -H"Content-type: text/plain" -d'duke' http://localhost:8080/jaxrs-beanvalidation/resources/ping mainifests as:


HTTP/1.1 400 Bad Request
Server: Payara Server  5.184 #badassfish
reason: size must be between 2 and 3
(...)

The 7kB ThinWAR was built and deployed with wad.sh in 3 seconds.

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


NEW: Online Workhop Effective WebApps without Frameworks is also coming to: MUC Airport.

Airport MUC workshops: Web (SPA, PWAs, Offline, Desktop, Mobile) Applications Essentials and Effective Web Applications. No migrations. #usetheplatform

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
realworldpatterns.com
...the last 150 posts
...the last 10 comments
License