Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>So, I hope this is what you want or at least pushs you in the right direction:</p> <p>In my controller, I have the following method:</p> <pre><code>@RequestMapping(value = "/test/createEntry", method = RequestMethod.POST) @ResponseBody public void doAndValidateSomething(@RequestBody @Valid ValidationFormModel, HttpServletResponse response) { try { testService.doSomething(model); } catch (NormalException e) { log.error(String.format("Error doing something! Values -&gt; name: %s, address: %s", model.getName(), model.getAddress(), e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } </code></pre> <p>And this is my exception handler (used in controller, too). Note the line <code>e.getBindingResult.getAllErrors()</code> here, which gives you a list of all errors. In my case, I decided to use only the first error via <code>iterator.next()</code>, but this is just wanted by me, feel free to use <code>getAllErrors()</code> only:</p> <pre><code>@ExceptionHandler(MethodArgumentNotValidException.class) public void validationException(MethodArgumentNotValidException e, HttpServletResponse response) throws IOException { response.getWriter().append(e.getBindingResult().getAllErrors().iterator().next().getDefaultMessage()); log.error("Validation failed!", e); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } </code></pre> <p>My model looks somewhat like this:</p> <pre><code>import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.constraints.Pattern; public class ValidationFormModel { @Length(max=50,min=2, message= "...") @NotEmpty(message = "....") private String name; @Length(max=250,min=1, message= "...") private String address; //constructor, getters and setters... } </code></pre> <p>And on client side, I use the following jquery / json to send my data via post and show the actual error. In your error handler, you could change the logic according to your need (I assume you want to show every error directly at the form input field or something):</p> <pre><code>var approveNewSend = function () { var newEntry = JSON.stringify({ name: $('#nameInput').val(), }); $.ajax({ url: "${pageContext.request.contextPath}/test/createEntry", type: "POST", data: newEntry, contentType: "application/json; charset=utf-8", dataType: "json" }) .success(function () { console.log('yay!'); }) .error(function (data) { $("#nerrorMessage").html("Error validating: " + data.responseText); }); }; </code></pre> <p>Hope this helps! Feel free to ask if something's not clear.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload