【问题标题】:Spring MVC with Hibernate Validator Mandatory for the database field, but not in the applicationSpring MVC with Hibernate Validator Mandatory for the database field,但不在应用程序中
【发布时间】:2013-12-25 06:32:02
【问题描述】:

BindingResult hasErrors() 在验证中出现问题。 我有这个代码:

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

实体类:

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

我需要在控制器中设置createdBy 的值,但总是在视图中显示“可能不为空”。 请帮忙。

Spring MVC 4、Hibernate 验证器 5、数据库 Oracle 11g

【问题讨论】:

  • 您能否提供更多详细信息?您可以在控制器中设置值,并且始终可以在视图中显示消息,那么问题是什么?
  • BindingResult 不知道 entity.setCreatedBy(auth.getName());并且 result.hasErrors() 为真,所以对象 Entity 没有被保存。

标签: spring hibernate spring-mvc hibernate-validator


【解决方案1】:

在 Spring MVC 调用 submit() 方法之前验证您的 entity 对象。 result 对象同时创建。这一行:

entity.setCreatedBy(auth.getName());

对result.hasErrors()的结果绝对没有影响。

【讨论】:

  • 如果createdBy 字段不是用户输入(而是代码提供的值),为什么还需要验证它?您可以从createdBy 中删除@NotNull。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多