3

I have a web application with HTML / jQuery which ic connected with AJAX / JSON to a backend system with Java EE / Spring MVC.

In the frontend, a Person can be created by fill in the form fields and then it is submitted and this jQuery code executed:

var person = $(this).serializeObject();
$.postJSON("add/", person, function(data) {
    alert("Person with ID "+data.person.id+"' added successfully");
});

In the best case, the Person is created and I'll get a Person object and I can access the values with data.person.*.

Now I want to validate the data which is sent to the backend system and in a case of an error, I want to display in the first step an alert error message.

I did this in the backend system:

@RequestMapping(value="add/", method=RequestMethod.POST)
public @ResponseBody Map<String, ? extends Object> addPerson(@RequestBody Person p, HttpServletResponse response) {
    Set<ConstraintViolation<Person>> failures = validator.validate(p);
    if (!failures.isEmpty()) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return validationMessages(failures);
    } else {
        Person person = this.personService.addPerson(p);
        return Collections.singletonMap("person", new SerialPerson(person.getId(), person.getName(), ...));
    }
}

// internal helpers
private Map<String, String> validationMessages(Set<ConstraintViolation<Person>> failures) {
    Map<String, String> failureMessages = new HashMap<String, String>();
    for (ConstraintViolation<Person> failure : failures) {
        failureMessages.put(failure.getPropertyPath().toString(), failure.getMessage());
        System.out.println(failure.getPropertyPath().toString()+" - "+failure.getMessage());
    }
    return failureMessages;
}

My Person object is annotated, and I get the System.out.println(failure.getPropertyPath().toString()+" - "+failure.getMessage()); on the console, that for example, "name - must be between 1-30 chars"

But how can create an alert message in jQuery in the frontend system?

Thank you in advance for your help & Best Regards.

Update: Link to the Spring MVC AJAX example, where I found the validationMessages method. But there is also no solution how to get the error message.

SOLUTION:

I have to call:

jQuery.ajax({
    'type': 'POST',
    'url': "add/",
    'contentType': 'application/json',
    'data': JSON.stringify(person),
    'dataType': 'json',
    'success': function(data) {alert("success");}, 
    'error': function(xhr) {alert(xhr.responseText);}
});

1 Answer 1

3

You can do something like this:

var person = $(this).serializeObject();
$.postJSON("add/", person, function(data) {

    if(data.person) {
       alert("Person with ID "+data.person.id+"' added successfully");
    }

    else {
       var errors = "";
       for(var key in data) if(data.hasOwnProperty(key)) {
           errors += data[key] + "\n";
       }

       alert(errors);
    }
});

You shouldn't need to send back a bad request either. Is this what you want?

UPDATE

You can use the code shown in Spring Source, but you'd have to use jQuery.ajax

jQuery.ajax({
   type: 'POST',
   url: "add/",
   data: person,
   dataType: "json",
   success: function(data) {
      alert("Person with ID "+data.person.id+"' added successfully");
   },
   error: function(XMLHttpRequest, textStatus, errorThrown) {
      var errorJSON = JSON.parse(XMLHttpRequest.responseText); //if this is JSON otherwise just alerting XMLHttpRequest.responseText will do

      var errors = "";
      for(var key in errorJSON) if(errorJSON.hasOwnProperty(key)) {
          errors += errorJSON[key] + "\n";
      }

      alert(errors);
   }
});
Sign up to request clarification or add additional context in comments.

8 Comments

This works if I remove the line response.setStatus(HttpServletResponse.SC_BAD_REQUEST); otherwise it does not work. But why is in the tutorial blog.springsource.com/2010/01/25/… this done?
@Tim My bad, as I was writing it I realized that I made a mistake. Conceptually it would make sense to send back a bad request since you encountered an error. However, I don't know how you would send back the error message details. (Maybe you could eval the textStatus... ugly). So in your case, you should remove the line because you do want the error messages back.
I think I have to put the error message inside the error response with code 400 = SC_BAD_REQUEST. And then there must be a way to get it in the frontend system. But I also have no idea...
I haven't tried to do it that way either. While conceptually more accurate, it's a little harder to deal with from the front-end.
I found this: src.springframework.org/svn/spring-samples/mvc-showcase/src/… - search for $("a[class=textLink]").click(function(){ and there is a $.ajax() call with success and error part, perhaps this is working? But I do not know how to convert my ``$.postJSON()` to $.ajax()
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.