문제

Problem with BindingResult hasErrors() in validation. I have this code:

@RequestMapping(value = "/entity", params = "form", method = RequestMethod.POST)
  public String submit(@Valid @ModelAttribute Entity entity, BindingResult result) {
  Authentication auth = SecurityContextHolder.getContext().getAuthentication();
  entity.setCreatedBy(auth.getName());
  if (result.hasErrors()) {
     //Here the error of createdBy is null
     return "entity/new";
  } else {
     entityService.save(entity);
     return "redirect:/entity/list";
  }
}

the entity class:

@Entity
@Table(name = "TABLE_X")
public class Entity implements Serializable {
   private static final long serialVersionUID = 1L;
   @Id
   @NotNull
   @Column(name = "primary_key")
   private String primaryKey;
   @NotNull
   @Column(name = "created_by")
   private String createdBy;
   //getters and setter
}

I need set the value of createdBy in controller but always show "may not be null" in view. Please help.

Spring MVC 4, Hibernate Validator 5, Database Oracle 11g

도움이 되었습니까?

해결책

You entity object is validated before Spring MVC invokes the submit() method. The result object is created at the same time. This line:

entity.setCreatedBy(auth.getName());

has absolutely no effect on the outcome of result.hasErrors().

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top