开发者

JavaScript - how to display error message from backend system based on Spring MVC

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);}
});


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);
   }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜