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.


Web Apps, SPA, PWA with vanilla Java Script (ES 6+), CSS 3 and WebStandards only. As simple as possible, but not simpler. See you at: (Progressive) Web apps, Single Page Apps and WebStandards airhacks workshops at MUC airport, Winter Edition

airhacks.fm the podcast:

Stay in touch: airhacks.news.

Comments:

Hi Adam,
there is also a similar header for warning messages. Called Warning:

https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.46
...
The Warning general-header field is used to carry additional information about the status or transformation of a message which might not be reflected in the message. This information is typically used to warn about a possible lack of semantic transparency from caching operations or transformations applied to the entity body of the message.
...

Greetings
Manuel

Posted by Manuel Blechschmidt on May 03, 2019 at 08:14 AM CEST #

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