2017-07-17 78 views
0

我想使用休眠驗證來驗證我的表單。顯示用於驗證的自定義消息

這是我的實體類:

@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"; 
} 

當我提交表單具有空值,我得到一個約束衝突異常,這是爲什麼?

+0

請分享您的堆棧跟蹤檢查.. –

回答

1

@NotEmpty:檢查值是否爲空也不爲空。因此,當您使用空值提交表單時,此驗證將被檢查並返回false。這就是您收到異常的原因。此驗證可用於收集,字符序列,映射或數組,它們不應該爲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(); 
    } 
}