开发者

Spring MVC + Ajax. How to display errors?

My spring web application is using ajax with spring, and it based in general on the demo application provided by spring:

https://src.springframework.org/svn/spring-samples/mvc-ajax/trunk/ (Additional info : http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/)

On the client-side I have a form (JSP):

<form:form modelAttribute="createLevel" action="createLevel" method="post">  
    <div class="form-item">  

    <form:label id="nameLabel" for="name" path="name" cssErrorClass="error">Level Name</form:label><br/>
     <form:input path="name" /><form:errors path="name" />
    </div>
    <div class="form-item">
    <input type="submit" value="Submit">  
    </div>  
</form:form>

I submit the form to the server by the following js method:

$("#createLevel").submit(function() {
        var level = $(this).serializeObject();
        $.postJSON("creat开发者_StackOverflow社区e.do", level, function(data) {
            alert(data);
        });
        return false;               
    });

On the server-side I have a validation as it shown below:

public final class LevelDto extends AbstractDto implements Serializable {
    private static final long serialVersionUID = 1L;

    private int id;

    @NotNull
    @Size(min = 2, max = 30)
    @LevelExistsConstraint(message = "Level with provided name is exists")
    private String name;
    // set; get;
}

And Controller

   @RequestMapping(value = "/admin/create.do", method = RequestMethod.POST)
    public @ResponseBody
Map<String, ? extends Object> createLevel(@RequestBody LevelDto level,
        HttpServletResponse response) {
    //JSR-303 
    Set<ConstraintViolation<LevelDto>> failures = validator.validate(level);

    if (!failures.isEmpty()) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return validationMessages(failures);

    } else {

        return Collections.singletonMap("id", 10);

    }
}

When I submit incorrect data to the server I see that all things are going on correctly - my validator is processing data, and the client is receiving an error response; moreover, in the response content I see the following:

{"name":"size must be between 2 and 30"}

My problem is that I do not know how to bind received error message correctly. Obviously, I can do it by js, but I thought that Spring is binding all error messages automatically to the view.

Any help is really appreciated.

-Cyril


create AjaxResponse class as a container of form field, status, and description.

class AjaxResponse {
    model; //form attribute
    status;  // OK or ERROR
    description; // message description such as error message
}

You can loop the failure validation result, generate List of AjaxResponse based on Failure Validation Result in JSON Format as a response of your controller action.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜