本文介绍了如何通过spring @Valid验证自定义默认错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DTO:

public class User {

    @NotNull
    private String name;

    @NotNull
    private String password;

    //..
}

控制器:

@RequestMapping(value = "/user", method = RequestMethod.POST)
public ResponseEntity<String> saveUser(@Valid @RequestBody User user) {
    //..
    return new ResponseEntity<>(HttpStatus.OK);
}

默认json错误:

{"timestamp":1417379464584,"status":400,"error":"Bad Request","exception":"org.springframework.web.bind.MethodArgumentNotValidException","message":"Validation failed for argument at index 0 in method: public org.springframework.http.ResponseEntity<demo.User> demo.UserController.saveUser(demo.User), with 2 error(s): [Field error in object 'user' on field 'name': rejected value [null]; codes [NotNull.user.name,NotNull.name,NotNull.java.lang.String,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.name,name]; arguments []; default message [name]]; default message [may not be null]],"path":"/user"}

我想为发生的每个错误使用我的自定义json.我该怎么做?

I would like to have my custom json for each error occured. How do I accomplish that?

推荐答案

您可以使用Errors/BindingResult对象执行验证.将Errors参数添加到您的控制器方法中,并在发现错误时自定义错误消息.

You can perform validation with Errors/BindingResult object.Add Errors argument to your controller method and customize the error message when errors found.

下面是示例示例, errors.hasErrors()在验证失败时返回true.

Below is the sample example, errors.hasErrors() returns true when validation is failed.

@RequestMapping(value = "/user", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<String> saveUser(@Valid @RequestBody User user, Errors errors) {
    if (errors.hasErrors()) {
        return new ResponseEntity(new ApiErrors(errors), HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<>(HttpStatus.OK);
}

这篇关于如何通过spring @Valid验证自定义默认错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 04:47