2

What is the correct way of implementing request body (JSON, XML) sent with POST or PUT method in Grails framework?

In Spring there is a @Valid annotation used to annotate method's argument and a bunch of field annotations (@NotNull e.g.) and exception mapper used to send validation response automatically. I can't find anything similar in Grails.

Opal
  • 81,889
  • 28
  • 189
  • 210
  • Grails has built in conversion from JSON/XML to Domain. And then a Domain can have constraints to validate the data. Is this what you're talking about? – Gregg Apr 22 '14 at 20:07
  • In general yes. But when this validation is being done? When entity is transformed from request's body to object? Or when object is saved to DB? What is spring's `@Valid` equivalent in grails? – Opal Apr 22 '14 at 20:11

1 Answers1

3

Grails performs validation via a Domain's constraints block. For example:

class User {
  String username
  String password

  static constraints = {
    username nullable: false, maxSize: 50, email: true
    password nullable: false, maxSize: 64
  }
}

See documentation.

Validation is performed during a couple of different actions on the domain:

user.save() // validates and only persists if no errors
user.validate() // validates only

Again, see the documentation. This is similar to what Spring's @Valid does. Looking at its documentation, it states:

Spring MVC will validate a @Valid object after binding so-long as an appropriate Validator has been configured.

What makes this basically the same as what Grails is doing is that it occurs after binding. For JSON/XML to Domain object conversion, it is really as simple as this:

def jsonObject = request.JSON
def instance = new YourDomainClass(jsonObject)

See this answer here.

Community
  • 1
  • 1
Gregg
  • 34,973
  • 19
  • 109
  • 214
  • Ok. So as far as I understood I need to do validation manually before saving the instance of an entity and if there are errors e.g. send them to client? Is there any mechanism for sending validation errors back to client (such as `@ExceptionHandler` in spring) ? – Opal Apr 24 '14 at 08:12
  • It would really help you to go through the documentation once and/or grab a book. If you look at my example above, no, you just call save() on the domain. If there are errors, it won't persist and you can send those errors back to the client from the controller. See this: http://grails.org/doc/2.1.0/ref/Tags/renderErrors.html – Gregg Apr 24 '14 at 12:36
  • 1
    Ok @Gregg. Thank You very much. I haven't gone through the documentation because I'm currently using grails only for simple proof of concept and don't know if there will be production usage. Nevertheless thank You once again for advice and patience. – Opal Apr 24 '14 at 12:38