显示自定义消息以进行验证

时间:2017-07-17 10:55:34

标签: hibernate

我正在尝试使用hibernate验证来验证我的表单。

这是我的实体类:

@Entity
@Table(name = "Employee")
@Proxy(lazy = false)
public class Employee implements Serializable
{
    private static final long serialVersionUID = 1L;

    @Column(name="name")
    @NotEmpty
    private String name;

    @Column(name="mobileNumber")
    @NotNull
    private Long mobileNumber;

    @Column(name="email")
    @Pattern(regexp="^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"  
    + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$")
    @NotEmpty
    private String email;
}

这是我的控制者:

@RequestMapping(value= "/employee/add", method = RequestMethod.POST)
public String addEmployee(@ModelAttribute("employee") @Valid Employee emp,
    BindingResult result, Model model)
{
    //validator.validate(emp, result);
    this.employeeService.addEditEmployee(emp);
    return "redirect:/employees";
}

当我提交带有空值的表单时,我得到一个约束违规异常,为什么会这样?

1 个答案:

答案 0 :(得分:1)

@NotEmpty:检查该值是否为空还是空。所以当您提交带有空值的表单时,正在检查此验证并返回false。这就是您获得异常的原因。此验证可用于收集, char序列,映射或数组,它们不应为null且大小> 0,否则会产生异常。如果使用此验证,则应仅发送非空值。

@NotEmpty(message="Value shouldnot be empty")
private String value;

然后在您的控制器类中,执行如下所示的检查

 @PostMapping("/addEmployee")
public @ResponseBody ResponseEntity<AppResponse> addEmployee(@RequestBody @Valid Employee emp, Errors errors) {
    AppResponse response = new AppResponse();
    try {

        if (errors.hasErrors()) {
            System.out.println(errors);
            List<ObjectError> list = errors.getAllErrors();
            List<String> msgList = new ArrayList<String>();
            String msg = null;
            for (ObjectError error : list) {
                msgList.add(error.getDefaultMessage());
                msg = String.join(",", msgList);
            }
            response.setStatusCode(417);
            response.setMessage(msg);
            response.setData(new ModelMap());
            return new ResponseEntity<AppResponse>(response, HttpStatus.NOT_FOUND);
        } else {
            return "redirect:/employees";
        }
    } catch (Exception e) {
        e.printStackTrace();
        return AppResponseOther.genericProblem();
    }
}