3

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

2
  • Could you please provide more details? You can set the value in controller and you can always show message on view, so what's the problem? Commented Dec 25, 2013 at 6:40
  • The BindingResult not know of entity.setCreatedBy(auth.getName()); and result.hasErrors() is true, so the object Entity is not saved. Commented Dec 25, 2013 at 6:47

1 Answer 1

2

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().

Sign up to request clarification or add additional context in comments.

1 Comment

Why do you need to validate the createdBy field if it is not a user input (but a value supplied by your code)? You could remove @NotNull from createdBy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.