title: How to validate request against XSD and return an error object?
body: <p>My task is to implement a webservice that:</p>
  
  <ul>
  <li>consumes an XML file on a POST endpoint</li>
  <li>in happy flow, it returns a DTO as JSON + HTTP 2xx</li>
  <li>the incoming XML file is validated against a XSD; if the validation fails, a JSON with a list of <em>all</em> validation errors is returned (including the line, column, error) with HTTP Bad request</li>
  <li>the application exposes two endpoints, only one of them should be validated</li>
  </ul>
  
  <p>I have started the implementation with Spring Boot + web, using regular @PostMapping which has "consumes" and "produces" set to application/xml and application/json, respectively. The usual flow works perfectly fine. Now, I stumbled upon the issue of validating the incoming payload. What I figured out:</p>
  
  <p>1) I have to validate the payload before it is converted (marshalled) to an object.</p>
  
  <p>2) Once validated, I have to either:</p>
  
  <ul>
  <li>allow further processing</li>
  <li>stop any further processing, write the error object to the response and set the status code to 400 Bad request</li>
  </ul>
  
  <p>My approaches were:</p>
  
  <p>1) using a RequestBodyAdvice, more specifically the beforeBodyRead method implementation. I had the following issue here: I don't know how to write anything to the output in case the validation fails.</p>
  
  <p>2) using a Filter (I've extended OncePerRequestFilter) - fortunately, I can read the request (request.getInputStream()) and write to the response (response.getOutputStream()).</p>
  
  <p>However, how can I do the selective filtering (as mentioned, I only want to validate one single endpoint)?</p>
  
  <p>Are there any other alternatives for placing the incoming request XSD validation? Is spring-web the appropriate choice here? Would you recommend some other library / framework?</p>